.

MVC Razor – working with combobox/dropdown controls

Rendering a dropdown in MVC with an id and preselected value etc.

Class

public class Ward 
{
    public int Ward_id{get ;set;}
    public string Ward_name{get ;set;}
    public List<Wards> GetAll() 
    {
        //code here
    }
}

 

Controller:

model.Wards = Ward.GetAll();
model.Wards.Insert(0,new Wards() { Ward_name="all", Ward_id = -1});
model.SelecteWardId = id;

View:

 

@Html.DropDownListFor(n => n.Wards, new SelectList(
    Model.Wards,"Ward_id","Ward_name", Model.SelecteWardId),
        new Dictionary<string, object> { { "id", "TheIdForTheDropdown" }
        { //can add click events etc here too 
  } })

this renders:

<select id="TheIdForTheDropdown" name="Wards"><option value="-1">all</option>
<option value="1">A</option>
<option selected="selected" value="2">B</option>
<option value="3">C</option>
</select>

2 Responses to this post.

  1. Posted by pietman on 18.12.12 at 11:48 am

    also:
    @{
    List
    items = new List ();
    items.Add(new SelectListItem { Text = “this”, Value = “that” });
    var Itemshere = new SelectList(items, “Value”, “Text”);
    }

    My List: @Html.DropDownList(“State”, Itemshere as SelectList, “Select a State”, new { id = “State” })
  2. Posted by Shawara on 18.12.12 at 11:48 am

    i like it

What's your thoughts on this?

*

Protected by WP Anti Spam