MVC3 DropDownListFor没有选择项(Mvc bug?)

时间:2012-09-03 13:37:00

标签: asp.net-mvc asp.net-mvc-3 html.dropdownlistfor mvc-editor-templates

我有简单的测试模型:

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

    }

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

在控制器中:

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")

当页面加载时我看到所选项目: enter image description here

很好。

但如果我添加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")

并更改 MyModelView

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

加载页面后,我会看到:enter image description here

为什么呢? MVC错误?

更新 这个真正的错误。 See

2 个答案:

答案 0 :(得分:8)

在创建所选项目列表时尝试此操作:

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

以下解释了为什么会发生这种情况:https://stackoverflow.com/a/11045737/486434

答案 1 :(得分:1)

使用@Model InnerModel更改此

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

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