ASP.NET MVC 2 - How can I get the selected value from a drop down into my view model?
I'm creating a drop down via
<%= Html.DropDownList("data.Language", Model.LanguageOptions) %>
and want to read back its value through automatic model binding into my LanguageModel viewmodel:
public ActionResult Save(LanguageModel data)
However, data.Language is null when the Save method is called.
How do I get the selected value from my data.Lan开发者_如何学JAVAguage dropdown into data.Language?
I don't know how your controller action and model look like but this definitely works:
Model:
public class LanguageModel
{
public string Language { get; set; }
public IEnumerable<SelectListItem> LanguageOptions
{
get
{
return new[]
{
new SelectListItem { Value = "en", Text = "English" },
new SelectListItem { Value = "fr", Text = "French" },
};
}
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new LanguageModel());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(LanguageModel data)
{
return View(data);
}
}
View:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("Language", Model.LanguageOptions) %>
<input type="submit" value="OK" />
<% } %>
<div><%= Html.Encode(Model.Language) %></div>
Of course if you are using ASP.NET MVC 2.0, the strongly typed DropDownListFor
helper is preferable.
get rid of the data.
<%= Html.DropDownList("Language", Model.LanguageOptions) %>
Or try:
<%= Html.DropDownListFor(m => m.Language, Model.LanguageOptions) %>
(although m.Langage may not be right - it depends on how your view model is set up)
精彩评论