Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC ViewModel and DropDownList

I have 2 properties in my ViewModel

class ViewModel1
{
    Dictonary<int, string> PossibleValues {get;set;}//key/value
    int SelectedKey {get;set}
}

I want to edit this using a Html.DropDownListFor

I want to get MVC to auto serialize the data into/from the ViewModel so I can the following

public ActionResult Edit(ViewModel1 model) ...

What's the best way to accomplish this?

like image 654
jameszhao00 Avatar asked Jan 30 '10 07:01

jameszhao00


People also ask

What is difference between DropDownList and DropDownListFor?

DropdownListFor is support strongly type and it name assign by lambda Expression so it shows compile time error if have any error. DropdownList not support this.

How do I bind a dropdown in dynamically MVC 4?

IEnumerable<SelectListItem> list = items. Select(c => new SelectListItem { Text = c. CURRENCY_SYMBOL, Value = c. ID.

How do you bind a static value to a DropDownList in MVC?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.


1 Answers

As womp said, a browser will only submit the selected value of a drop down list. This is easily bound by the default model binder, see below.

If you are not editing the PossibleValues list on the client then there is no need to submit them back. If you need to repopulate the list then do it server side in your post action by using the same method you originally populated the Dictionary with.

For example in you page:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewModel1>" %>
<!-- some html here -->
<%= Html.DropDownListFor(x => x.SelectedKey, new SelectList(Model.PossibleValues, "key", "value"))%>

In your controller

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Edit() {
 var model = new ViewModel1 {
   PossibleValues = GetDictionary()  //populate your Dictionary here
 };
 return View(model);
}

[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Edit(ViewModel1 model) { //default model binding
  model.PossibleValues = GetDictionary();  //repopulate your Dictionary here
  return View(model);
}

Where GetDictionary() is a method that returns your populated Dictionary object.

See this similar question for more details

like image 121
David Glenn Avatar answered Sep 18 '22 18:09

David Glenn