1

I have this selectlist:

controller:

 ViewBag.SagId = new SelectList(db.Sags, "Id", "Emne", 7);

list and everything works as suposed to, but the selected value is not == 7,

View:

 @Html.DropDownListFor(x => x.SagId,(IEnumerable<SelectListItem>) ViewBag.SagId,
new
{

    @class = "selectpickers",
    data_show_subtext = "true",
    data_live_search = "true"

})

its probably some stupid thing i have missed?

  • Model binding works by binding to the value of your property. Set the value of `SagId` to `7` in the GET method before you pass the model to the view and it will be selected. The 4th parameter of the `SelectList` constructor is ignored when you bind to a property –  May 02 '17 at 12:17
  • i don't want it to always be 7, just a test wanted it to be an int that can change depending on what site they visit. – user3759748 May 02 '17 at 12:27
  • It does not matter what the actual value is. You need to set the value of property `SagId` and if that matches one of the option values it will be selected (otherwise the first option will be selected because something has to be) - that is how model binding works. –  May 02 '17 at 12:30
  • hmm there is a value = 7, on SagsId. first think i was looking for aswell. – user3759748 May 02 '17 at 12:32
  • so you're saying, i should set it in my get? how would you do that ? – user3759748 May 02 '17 at 12:33
  • `var model = new YourModel(){ SagId = 7 }; return View(model);` –  May 02 '17 at 12:37
  • yes, oka thanks for your help. Got it working now. if u want you can make an answer i will accept it. :) @StephenMuecke – user3759748 May 02 '17 at 12:48

1 Answers1

0

Model binding works by binding to the value of your model property. You need to set the value of property SagId in the controller before you pass the model to the view.

Your code in your controller method should be something like

var model = new YourModel()
{
    SagId = 7
};
ViewBag.SagId = new SelectList(db.Sags, "Id", "Emne");
return View(model);

Note that there is not point setting the 4th parameter in the SelectList constructor. It's ignored when binding to a model property because internally the DropDownListFor() method builds its own IEnumerable<SelectListItem> and sets the Selected property based on the value of the property your binding to.

Note also that you should not use the same names for the property your binding to (refer Can the ViewBag name be the same as the Model property name in a DropDownList?), and I strongly recommend that you use a view model, especially when editing, and that view model will contain a property public IEnumerable<SelectListItem> SagList { get; set; } and in the view it will be @Html.DropDownListFor(m => m.SagId, Model.SagList, new { ... })

Community
  • 1
  • 1