DropDownList - selectedValue without PostValue is not selected
i use asp.net mvc 2 and i have a problem with the DropDownListFor helper. My ViewModel contains a SelectList with all required开发者_开发百科 Values und 1 SelectedValue. When i use the DropDownListFor helper in my View the SelectedValue is not selected! Then i select a other Value and submit the form, on the next rendering in the PostedValue selected. What is the problem on the first Rendering?
<%=Html.LabelFor(m => m.Test)%>
<%=Html.DropDownListFor(m => m.Test, Model.TestList, new { tabindex = 1, @class = "selectbox" })%>
<%=Html.ValidationMessageFor(m => m.Test, null, new {@class = "text-hide", id = "Error-Test"})%>
From what you've provided it is impossible to say why it doesn't work as you haven't shown neither the controller, nor the view model.
Here's an example that works:
Model:
public class MyModel
{
public string Test { get; set; }
public IEnumerable<SelectListItem> TestList
{
get
{
return new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "text 1" },
new SelectListItem { Value = "2", Text = "text 2" },
new SelectListItem { Value = "3", Text = "text 3" },
}, "Value", "Text", Test);
}
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyModel { Test = "2" });
}
}
View:
<%: Html.DropDownListFor(x => x.Test, Model.TestList) %>
精彩评论