c# - Selected Value not selected in a DropDownListFor of SelectList of SelectListItems -


the dropdownlistfor not selecting selectlistitem specifying should selected. unable figure out why parameters appear correct.

viewmodel:

public class schemesviewmodel {     public int schemeid { get; set; }     public selectlist schemes { get; set; } } 

controller (select list preparation):

var schemes = schememanager.getuserschemes(this.userid);  var selectlistitems = schemes.select(x => new selectlistitem() { value = x.id.tostring(), text = x.name, selected = (x.id == 2) });  var vm = new userschemesviewmodel() {      schemes = new selectlist(selectlistitems, "value", "text", selectedvalue: selectlistitems.firstordefault(x => x.selected == true).value) };  return partialview("_userschemes", vm); 

view:

note: select option value of 2 not selected!

 @html.dropdownlistfor(x => x.schemeid, model.schemes) 

setting selected property of selectlistitem ignored dropdownlistfor() method. internally method build new ienumerable<selectlistitem> using value of text properties of existing selectlist , sets new selected property based on value of property binding to. need set value of schemeid before pass model view.

there no point creating second identical selectlist first 1 (its unnecessary overhead).

modify code to

public class schemesviewmodel {     public int schemeid { get; set; }     public ienumerable<selectlistitem> schemes { get; set; } } 

controller

var schemes = schememanager.getuserschemes(this.userid); var selectlistitems = schemes.select(x => new selectlistitem() {     value = x.id.tostring(),      text = x.name }); var vm = new userschemesviewmodel() {     schemes = selectlistitems,     schemeid = 2 }; return partialview("_userschemes", vm); 

now if 1 of options has value="2" option selected when first render view.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -