如何在 ViewModel 中 post 个对象?

How to post objects in ViewModel?

我有这个视图模型 class,它有一个整数 ID 和一个对象类型。

public class MyViewModel
{
    [Required]
    public int MyId { get; set; }

    public MyObject MyObject { get; set; }
}

MyObject 模型是:

public class MyObject 
{
    [Key]
    public int ObjId { get; set; }

    public int Number { get; set; }
    public string Name { get; set; }

}

这个控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}

观点是:

@model MyProject.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        @Html.LabelFor(model => model.MyId , htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("MyId", null, "Select", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.MyId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.MyObject.Number, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.MyObject.Number, new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Number, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.MyObject.Name , htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.MyObject.Name , new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Name , "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" formaction="@Url.Action("Create")" />
        </div>
    </div>
}

当我post 数据到控制器时,它识别 MyId 值但不填充 MyObject 参数。任何关于如何 post 使用 ViewModel 的对象的建议?

假设视图顶部有 @model MyViewModel,则无需将其复杂化。

提交视图

<input type="submit" value="Create" class="btn btn-default" />

并更改 post 方法的签名

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}

然后应绑定视图模型。

尝试以下:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId,MyObject, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
}

您没有在 Bind(include)

中包含 MyObject