DeeRain
DeeRain

Reputation: 1354

MVC3 DropDownListFor not select item (Mvc bug?)

I have simple test model:

  public class MyModel
    {
        public InnerModel InnerModel { get; set; }

    }

    public class InnerModel
    {
        public int Value { get; set; }
    }

In controller:

public ActionResult Index()
{
    var model = new MyModel();

    model.InnerModel = new InnerModel { Value = 3 };

    return View("MyModelView", model);
}

MyModelView:

@model MyModel

@{
    var items = new List<SelectListItem>()
                    {
                        new SelectListItem {Text = "one", Value = "1"},
                        new SelectListItem {Text = "two", Value = "2"},
                        new SelectListItem {Text = "three", Value = "3"}
                    }; }


@Html.DropDownListFor(m=>m.InnerModel.Value,items,"no_selected")

When page load i see selected item: enter image description here

It's good.

But if I add EditorTemplate InnerModel.cshtml:

@model InnerModel

    @{
        var items = new List<SelectListItem>()
                        {
                            new SelectListItem {Text = "one", Value = "1"},
                            new SelectListItem {Text = "two", Value = "2"},
                            new SelectListItem {Text = "three", Value = "3"}
                        }; }


    @Html.DropDownListFor(m=>m.Value,items,"no_selected")

And change MyModelView:

@model MyModel
@Html.EditorFor(m=>m.InnerModel,"InnerModel")

When page loaded i see: enter image description here

Why? MVC bug?

UPDATE: This real bug. See

Upvotes: 1

Views: 3623

Answers (2)

Ian Routledge
Ian Routledge

Reputation: 4042

Try this instead when creating the list of select items:

var items = new SelectList(
        new[] 
        {
            new { Value = "1", Text = "one" },
            new { Value = "2", Text = "two" },
            new { Value = "3", Text = "three" },
        }, 
        "Value", 
        "Text", 
        Model.Value
    )

Here is an explanation of why this happens: https://stackoverflow.com/a/11045737/486434

Upvotes: 8

BigMike
BigMike

Reputation: 6863

with the @Model InnerModel change this

@Html.DropDownListFor(m=>m.InnerModel.Value,items,"no_selected")

to

@Html.DropDownListFor(m=>m.Value,items,"no_selected")

Upvotes: 1

Related Questions