我有一个MVC控制器,在post方法中,模型始终返回为空。我不确定这是否是因为我在表单中使用了部分视图。
有什么想法,为什么模型没有被返回到控制器?
模型
加载模型
public List<Group> GetStaticMeasures(int businessUnitID)
{
List<Group> groups = ctx.Groups
.Include("Datapoints")
.Where(w => w.BusinessUnitID.Equals(businessUnitID))
.OrderBy(o => o.SortOrder).ToList();
groups.ForEach(g => g.Datapoints = g.Datapoints.OrderBy(d => d.SortOrder).ToList());
return groups;
}
控制器
public ActionResult Data()
{
ViewBag.Notification = string.Empty;
if (User.IsInRole(@"xxx\yyyyyy"))
{
List<Group> dataGroups = ctx.GetStaticMeasures(10);
return View(dataGroups);
}
else
{
throw new HttpException(403, "You do not have access to the data.");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Data(List<Group> model)
{
ViewBag.Notification = string.Empty;
if (User.IsInRole(@"xxx\yyyyyy"))
{
if (ModelState.IsValid)
{
ctx.SaveChanges(model);
ViewBag.Notification = "Save Successful";
}
}
else
{
throw new HttpException(403, "You do not have access to save the data.");
}
return View(model);
}
主视图
@model List<Jmp.StaticMeasures.Models.Group>
<div class="row">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="large-12">
<div class="large-8 large-centered columns panel">
@foreach (var g in @Model)
{
<h2>@g.Name</h2>
foreach (var d in g.Datapoints)
{
@Html.Partial("Measures", d)
}
<hr />
}
<input type="submit" class="button" value="Save Changes"/>
</div>
</div>
}
</div>
局部视图
@model Jmp.StaticMeasures.Models.Datapoint
@Html.HiddenFor(d => d.ID)
@Html.HiddenFor(d => d.Name)
@Html.HiddenFor(d => d.SortOrder)
@Html.DisplayTextFor(d => d.Name)
@Html.EditorFor(d => d.StaticValue)
@Html.ValidationMessageFor(d => d.StaticValue)
显示连续ID的渲染HTML
@
符号也去掉了吗?那里不应该有它。另外,请检查生成的 HTML,确保您可以在输入元素上看到连续的索引。如果DataPoint
ID 不是连续的,则需要生成额外的Html.Hidden
字段,如 此文章 中的“非连续索引”部分所述。 - John H