如何将关系数据绑定到ASP.net MVC中的模型?

时间:2011-02-14 23:33:11

标签: asp.net-mvc-3

我正在尝试为ASP.net MVC 3中的对象创建一个编辑器。它看起来像这样:

<div class="editor-label">
    @Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.foo)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.foo)
    @Html.ValidationMessageFor(model => model.foo)
</div>
@if (Model.Items.Count > 0)
{
<table>          
    @foreach (var ii in Model.Items)
    { @Html.EditorFor(item => ii) }
</table>
}

在此示例中,Items是另一种对象的列表。问题是,当模型从视图中编辑回来时,数据更改为Model.Items不存在,而数据更改为Name和foo工作。如何才能使Item的数据正确绑定?

1 个答案:

答案 0 :(得分:2)

模特课:

public class HomeControllerModel
{
    public string Name { get; set; }
    public string foo { get; set; }
    public List<string> Items { get; set; }

    public HomeControllerModel()
    {
        Items = new List<string>();
    }
}

控制器类:

public class HomeController : Controller
{


    [HttpGet]
    public ActionResult Index()
    {
        var model = new HomeControllerModel();
        model.Name = "LukLed";
        model.foo = "bar";
        model.Items.Add("AAA");
        model.Items.Add("BBB");
        model.Items.Add("CCC");
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(HomeControllerModel model)
    {
        return View(model);
    }

查看:

@using MvcApplication4.Controllers
@model HomeControllerModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        <form action="/Home/Index" method="post">
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.foo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.foo)
            @Html.ValidationMessageFor(model => model.foo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Items)
        </div>
        <input type="submit" value="Submit" />
        </form>
    </div>
</body>
</html>

您不必遍历Items