Pergunta

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

Foi útil?

Solução

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

Outras dicas

with the @Model InnerModel change this

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

to

@Html.DropDownListFor(m=>m.Value,items,"no_selected")
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top