Drop down List from Viewbag not following selected property - asp.net-mvc-5

I have a dropdownList that will be populated by a viewbag carrying a List values containing "Text" and "Value" property that is set by a loop.
List<SelectListItem> year = new List<SelectListItem>();
for (var i = 1990; i <= DateTime.Now.Year; i++)
{
year.Add(new SelectListItem
{
Text = i.ToString(),
Value = i.ToString()
});
}
ViewBag.Year = year;
And in my view:
#Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text", Model.Birthday.Year), htmlAttributes: new { #class = "form-control", style = "width: 80px" })
Nothing happens.

Try
#Html.DropDownListFor(model => model.Year, new SelectList(#ViewBag.Year, "Value", "Text", Model.Birthday.Year), new { #class = "form-control", style = "width: 80px" })
It will work as expected.

I used script instead
$('#Year option')
.removeAttr('selected')
.filter('[value=#Model.Birthday.Year]')
.attr('selected', true)

Related

Complete drop down list when editing whit a Joining the table in Asp.net MVC 5

I have three tables in the name of Person and City and Evidence whose table has person a few columns including FirstName , LastName ,cityid (cityID), EvidenceID that id of the table (EvidenceID), the EvidenceID fields and the cityID are foreign keys, and to the id table City maps, Evidence connected
Now I want to have two combo boxes (tag) when I'm creating a new person, so that they can list them in place of the ID of the city and the id of the Evidence , and list them in the cowboy box.
Also, when editing, I want to know that when I go to the editing form, you can see the name of the city and the person's profile on the cowboys, and we can also see and edit the other cobblestones.
please guide me.
[HttpGet]
public ActionResult EditPerson(int id)
{
var q = (from a in db.Person
where a.ID.Equals(id)
select a).SingleOrDefault();
if (q != null)
{
return View(q);
}
else
{
return RedirectToAction("ShowPerson", "Home");
}
}
[HttpPost]
public ActionResult EditPerson(Person per)
{
var q = (from a in db.Person
where a.ID.Equals(per.ID)
select a).SingleOrDefault();
q.FirstName = per.FirstName;
q.LastName = per.LastName;
q.UserName = per.UserName;
q.EvidenceID = per.EvidenceID;
q.Mobile = per.Mobile;
q.Stutus = false;
q.CodeMelli = per.CodeMelli;
q.CityID = per.CityID;
q.Address = per.Address;
q.Access = per.Access;
q.Email = per.Email;
q.Image = per.Image;
db.Person.Attach(q);
db.Entry(q).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("ShowPerson", "Home");
}
[HttpGet]
public ActionResult CreatePerson()
{
return View();
}
[HttpPost]
public ActionResult CreatePerson(Person per)
{
Person p = new Person();
p.FirstName = per.FirstName;
p.LastName = per.LastName;
p.UserName = per.UserName;
p.EvidenceID = per.EvidenceID;
p.Mobile = per.Mobile;
p.Stutus = false;
p.CodeMelli = per.CodeMelli;
p.CityID = per.CityID;
p.Address = per.Address;
p.Access = per.Access;
p.Email = per.Email;
p.Image = per.Image;
db.Person.Add(p);
db.SaveChanges();
return RedirectToAction("ShowPerson", "Home");
}
code in view edit :
<div class="form-group">
#Html.LabelFor(model => model.CityID, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.CityID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CityID, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.EvidenceID, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.EvidenceID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EvidenceID, "", new { #class = "text-danger" })
Your question is not being understood but what you need is a dropdownlist from three different models as i'm guessing...
try this in your own domain:
var dataForDL = _db.ModelName.Select(a => new
{
Text = a.PersonName +" "+ a.Evidence.Name +" "+ a.City.CityName,
Value = a.Id
}).ToList();
ViewBag.DropdownListForModel = new SelectList(dataForDL, "Value", "Text");
In the view.cshtml
#Html.DropDownList("DropdownListForModel", null, "-- Please Select Something --", htmlAttributes: new { #class = "form-control" })

Custom validation are not executing on focus change of applied control but works well in case of form submit

I am using normal mvc textboxfor on strong view, I have created custom validation attribute (the detailed code explained below).
On form submit everything works fine. In case if validation fails by natural it shows error message as configured.
Now when I enter the correct value inside text box I expect the error message to be vanished automatically but this does not happen until I post the form
JS File
$.validator.addMethod('validaterequiredif', function (value, element, parameters) {
var id = parameters['dependentproperty'];
var clickValue = $("input[name=" + id + "]:checked").val();
// get the target value (as a string,
// as that's what actual value will be)
var targetvalue = parameters['targetvalue'];
if (clickValue == targetvalue) {
if (value == null) {
return false;
}
else {
return $.validator.methods.required.call(
this, value, element, parameters);
}
}
else {
return true;
}
});
$.validator.unobtrusive.adapters.add(
'validaterequiredif',
['dependentproperty', 'targetvalue'],
function (options) {
options.rules['validaterequiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['validaterequiredif'] = options.message;
});
Server side custom validator class as below
public class ValidateRequiredIf : ValidationAttribute, IClientValidatable
{
protected RequiredAttribute _innerAttribute;
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public bool AllowEmptyStrings
{
get
{
return _innerAttribute.AllowEmptyStrings;
}
set
{
_innerAttribute.AllowEmptyStrings = value;
}
}
public ValidateRequiredIf(string dependentProperty, object targetValue)
{
_innerAttribute = new RequiredAttribute();
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
// trim spaces of dependent value
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
{
dependentValue = null;
}
}
// compare the value against the target value
if ((dependentValue == null && TargetValue == null) ||
(dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
{
// match => means we should try validating this field
//if (!_innerAttribute.IsValid(value))
if (value == null)
// validation failed - return an error
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "validaterequiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
}
Model property
[ValidateRequiredIf("IsFeederSelected", "True", ErrorMessage = "Please select atleast one feeder")]
public List<string> selectedMeterName { get; set; }
Strongly typed view
<div class="meterTextboxRadio col-md-4">
<p>
#Html.RadioButtonFor(m => m.IsFeederSelected, true, new { #class = "radio", #Name = "IsFeederSelected", value = "meter", id = "rdbMeterConsumption", #checked = "checked" })
<span> Feeder</span>
#Html.RadioButtonFor(m => m.IsFeederSelected, false, new { #class = "radio", #Name = "IsFeederSelected", value = "group", id = "rdbGroupConsumption",style= "margin-left: 30px;" })
<span> Group</span>
</p>
<div class="group dropdownhidden" id="MeterNameConsumption" style="margin-top:4px;">
#Html.DropDownListFor(m => m.selectedMeterName, Model.MeterName
, new { #class = "chosen-select" ,#id= "ddlConsumptionMeterName", multiple = "multiple", Style = "width:100%", data_placeholder = "Choose Feeders.." })
<span class="highlight"></span> <span class="bar"></span>
</div>
<div class="group dropdownhidden" id="GroupNameConsumption" style="margin-top:4px;">
#Html.DropDownListFor(m => m.selectedGroupName, Model.GroupName
, new { #class = "chosen-select", #id = "ddlConsumptionGroupName", multiple = "multiple", Style = "width:100%", data_placeholder = "Choose Group.." })
<span class="highlight"></span> <span class="bar"></span>
</div>
#Html.ValidationMessageFor(m => m.selectedMeterName, "", new { #class = "error" })
#Html.ValidationMessageFor(m => m.selectedGroupName, "", new { #class = "error" })
</div>
Please provide some inputs for the same
Thanks.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'SupervisingPhysician'

In PatientViewModel
public IEnumerable<SelectListItem> SupervisingPhysician { get; set; }
In PatientController
// Supervising Physicians
List<SelectListItem> listSelectSPListItems = new List<SelectListItem>();
foreach (Physician physician in db.Physicians.Where(p => p.IsSupervising == true))
{
SelectListItem selectSPList = new SelectListItem()
{
Text = physician.FirstName +" "+ physician.LastName,
Value = physician.Id.ToString()
};
listSelectSPListItems.Add(selectSPList);
}
ViewBag.SupervisingPhysicians = new SelectList(listSelectSPListItems,"Value","Text");
In View
#Html.DropDownListFor(x => x.SupervisingPhysician, (SelectList)ViewBag.SupervisingPhysicians, htmlAttributes: new { #class = "form-control col-md-4" })
Error:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'SupervisingPhysician'.

Umbraco 7 searchCriteria with all fields

Hi i have search on Umbraco 7 and it works OK, but i have to add a lot of search fields to index and it´s not practic. How can i search through all fields?
#{
string searchQuery = Request["query"];
if (String.IsNullOrWhiteSpace(searchQuery))
{
searchQuery = "";
}
var searcher = ExamineManager.Instance;
var searchCriteria = searcher.CreateSearchCriteria();
var query = searchCriteria.GroupedOr(new[] {
"nodeName",
//"packSizes",
"name",
"title",
"bodyText",
"body",
"field1",
"field2",
"field3",
"field4",
"field5",
"field6"
}, searchQuery).Compile();
var SearchResults = searcher.Search(query).Where(x => x["__IndexType"] == "content").ToList(); } #if (SearchResults.Any()) {
<ul class="search-results-box">
#foreach (var result in SearchResults)
{
var node = Umbraco.TypedContent(result.Id);
var pathIds = result["__Path"].Split(',');
var path = Umbraco.TypedContent(pathIds).Where(p => p != null).Select(p => new { p.Name }).ToList();
if (node != null)
{
<li>#node.Name</li>
}
}
</ul> }
You can add an event to the indexing command to concatenate all of the fields into one large field at indexing time, and just search that one field.
To hook into the event, in your OnApplicationStarting event handler, do the following:
ExamineManager.Instance.IndexProviderCollection["YOUR INDER NAME HERE"].GatheringNodeData += SetSiteSearchFields;
And then for the function, you can do something like this, combining all of the fields int a single field:
void SetSiteSearchFields(object sender, IndexingNodeDataEventArgs e)
{
//grab some fields
var combined = e.Fields["field1"] + " " + e.Fields["field2"];
//add as new field
e.Fields.Add("searchField", combined);
}
This would then give you a field called "searchField" that you could search, making your search much simpler.

Not able to assign selected value to Html.Dropdownlist MVC 4

While user retrieves his profile information from database, i am not able to bind dropdownlist with appropriate value.
User's gender is Female. While user retrieves information on a button click, the dropdownlist loads default values as "Male", "Female" and finally "Other". But, i want it to render with "Female and not male. here is my code.
Button click on the form to retrieve details
case "btnGo":
IntialStage();
item = onjLoad.ReadLoadPatientData(controlID["FirstrName"].ToString().Replace(",",""));
ViewData["PatientCharNumber"] = item.ChartNumber;
break;
}
loading dropdown value InitialStage()
IEnumerable<BindindClass> gender = onjLoad.LoadGenderMaster();
ViewData["GenderMaster"] = from c in gender
select new SelectListItem
{
Text = c.Text,
Value = c.Value,
};
View
#Html.DropDownListFor(m => m.Gender, (IEnumerable<SelectListItem>)ViewData["GenderMaster"])
Follow the below sample which i have did to show the selected value in dropdown,
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewData["CountryList"], new { id = "card_country", #class = "donation-ddlcountry" })
`public void CountryList(string countryCode)
{
string path = Server.MapPath(#"~\Country.xml");
IEnumerable result = from x in XElement.Load(path).Elements("country")
select x;
var listItems = new List<SelectListItem>();
foreach (var xElement in result)
{
listItems.Add(new SelectListItem
{
Text = xElement.Element("text").Value,
Value = xElement.Element("value").Value
});
}
if (countryCode == string.Empty)
{
var selected = listItems.Where(x => x.Value == "US").First();
selected.Selected = true;
}
else
{
var selected = listItems.Where(x => x.Value == countryCode).First();
selected.Selected = true;
}
ViewData["CountryList"] = listItems.ToList();
}`

Resources