【发布时间】:2017-06-06 14:24:41
【问题描述】:
我有一个带有整数 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>
}
当我将数据发布到控制器时,它会识别 MyId 值但不填充 MyObject 参数。任何建议如何使用 ViewModel 发布对象?
【问题讨论】:
-
显示完整视图,以便我们了解您尝试发布数据的方式。
-
@BarryO'Kane:我已经更新了视图
标签: c# asp.net-mvc-5 asp.net-mvc-viewmodel