Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.DropDownListFor() - How to set default selected value for a strongly typed view?

Using ASP.NET MVC 3, I have been struggling to set the selected value for dropdown using the help Html.DropDownListFor() function for a strongly typed view.

The code for the models look like this:

public class ResourceView
{
   ...
   public Language Language { get; set; }
}

public class Language
{
   public string DisplayName { get; private set; }      
   public string Code { get; private set; }    
   public override string ToString() {  return DisplayName;  }
}

and within the view:

@Html.DropDownListFor(model => model.Language, 
  new SelectList(ViewBag.AllPossibleLanguages, 
    "Code", "DisplayName", Model.Language.Code))

There are a few workarounds, such as using

@Html.DropDownList("LanguageCode", 
   new SelectList(ViewBag.PossibleLanguages,
      "Code", "DisplayName", Model.Language.Code))

and curiously enough, the code above won't work if the first parameter is set as "Language", same as the name of the property in the model.

I can also do like this

@Html.DropDownListFor(model => model.Language, 
  new SelectList(ViewBag.AllPossibleLanguages))

which will work as well with the appropriate selected value, however only the ToString() value of the Language class will be displayed and the actual language code that i want in the option tags won't be set, which is not surprising as there is nothing identify that the Code field should be used as the value attribute.

I can also solve this using a jquery event handler that selects the appropriate value afterwards. However I am curious as to why this doesn't work as intended and would like to solve it properly if possible.

like image 605
Can Gencer Avatar asked Oct 12 '22 08:10

Can Gencer


1 Answers

The first argument for @Html.DropDownListFor is the property of your model the selected value will be bound to on Post. When you say @Html.DropDownListFor(model => model.Language) the default binder won't able to figure which property in your Language class it needs to bind the selected value which in the case of dropdown list will always be a single string or integer. For the same reason @Html.DropDownList("LanguageCode") works.

You can always extended the default model binder if you would like to change the behavior.

Edit:

You could try, which I believe should solve your problem in this case.

@Html.DropDownListFor(model.Language.Code, new SelectList(ViewBag.AllPossibleLanguages))
like image 166
sarvesh Avatar answered Oct 15 '22 11:10

sarvesh