如何在ViewModel中发布对象?

时间:2017-06-06 14:24:42

标签: c# asp.net-mvc-5 asp.net-mvc-viewmodel

我的viewmodel类有一个整数Id和一个对象类型。

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

    public MyObject MyObject { get; set; }
}

MyObject Model是:

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

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

2 个答案:

答案 0 :(得分:1)

假设您在视图顶部有@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!
}

然后应绑定视图模型。

答案 1 :(得分:0)

尝试以下:

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

您未在MyObject

中加入Bind(include)