1

我有简单的测试模型:

  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);
}

我的模型视图:

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

当页面加载我看到选定的项目: 在此处输入图像描述

很好。

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

加载页面时,我看到:在此处输入图像描述

为什么?MVC 错误?

更新: 这个真正的错误。

4

2 回答 2

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

于 2012-09-03T13:59:44.397 回答
1

用@Model InnerModel 改变这个

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

@Html.DropDownListFor(m=>m.Value,items,"no_selected")
于 2012-09-03T13:47:24.260 回答