views:

40

answers:

1

Hello Community,

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"})%>
+1  A: 

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) %>
Darin Dimitrov