Advertise here


Tag cloud


 

Related articles

Regex link removal script

Using MVC DropDownListFor Html helper

Set Start Index & Max Rows

Convert int array to string array

Make navigation elements hover over flash.

Using MVC DropDownListFor Html helper

January 25th, 2012 in Web Development

Comments

You might have been mislead when using DropDownListFor method when you wanted to set the selected item or it is just me. I thought you can use the SelectList function fourth parameter to set the selected value, as it says in the documentation but this does not work because data is binded to the data object.

If the object or property in the model is empty and it used as an int then it will default to zero, so the item with the value zero will be selected.

So naturally all you need to do is set the property in the model to the value you want  and it will select the correct default value in the list.

Example below:

@{
//set the username to be selected
Model.Post.UserId = Model.GetUserId;
}
//Outputs a list of userid
@Html.DropDownListFor(model => model.Post.UserId, new SelectList(Model.Users, "Id", "Name"))

Sounds so simple and straight forward now, but is amazing how something small can distract you from the obvious answer sometimes.


Tags: , ,

Comments


Web Design Essex | Richard Kotze – Web Technology, Design and Development powered by WordPress | Entries (RSS)