希望有人能帮助我。我是 MVC 的新手,来自 winforms/console/vb6background。
如果这个问题已经得到解答,我深表歉意,我正在努力了解如何解决以下问题。
我有一个 View 模型:
public class testvm
{
public int id { get; set; }
public DateTime date { get; set; }
public student studentID { get; set; }
public testvm() { }
public testvm (student s)
{
studentID = s;
}
}
我在将此 ViewModel 传递给 View 之前预填充它的学生子对象。
学生模型:
public class student
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
我遇到的问题是,当模型返回到创建 HTTP post 方法时,学生子对象为空。
Controller 代码:
// GET: testvms/Create
public ActionResult Create(int sId)
{
student a = db.students.Find(sId);
testvm b = new testvm(a);
return View(b);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,date,student")] testvm testvm)
{
if (ModelState.IsValid)
{
db.testvws.Add(testvm);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(testvm);
}
查看代码:
@model WebApplication2.Models.testvm
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>testvm</h4>
<hr />
@Html.HiddenFor(model => model.studentID.ID)
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.date, "", 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" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
View 上的模型对象填充了学生信息。当它传回 Create POST Controller 时,学生子对象为空!
有人可以告诉我哪里出错了或实现此目标的正确方法吗?
我的申请表有很多表格,都需要预先填写学生信息。每个学生都会有许多表格需要为他们填写。
非常感谢, 罗布
最佳答案
对于域模型中的每个属性(在您的情况下为 testvm),您的 View (或用于 ID 或其他非用户 ui 数据的 HiddenFor)上必须有一个 EditorFor 或 Input 元素(如 TextBoxFor 等)。这可能很痛苦在 MVC 中绑定(bind)嵌套模型,因为 DefaultModelBinder 可能无法绑定(bind)整个对象。但是,更安全的方法是仅在 View 中公开所需的属性,如
@Html.HiddenFor(model => model.studentID.ID)
@Html.HiddenFor(model => model.studentID.Name)
和后来的 Controller 端
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(testvm testvm)
{
var originalobj=db.get //get fresh copy from data store
originalobj.Name=testvm.Name;
// ...other properties
//perform required operations on originalobj
}
您可以将 AutoMapper 用于此目的
Mapper.CreateMap<testvm,testvm>();
originalobj=Mapper.Map<testvm,testvm>(testvm,originalobj);
您可以在以下位置找到有关 Automapper 的更多信息: https://github.com/AutoMapper/AutoMapper/wiki/Getting-started
关于c# - HTTP post 上的 MVC 模型子对象为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29607511/