我有一条这样的路线:
Conference/Committees/1
在该页面中,它循环显示各次会议的委员会(会议ID = 1)。
我有一个局部视图,该视图为选定委员会呈现了一个编辑样式页面,其路由如下:
Conference/Committees/1?committeeId=2
在调试中,模型数据是正确的,并且委员会的Id =2。但是,当我使用以下Razor语句时:
@Html.HiddenFor(model => model.Id)
使用以下模型:
@model munhq.Models.Committee
隐藏的输入的值为“ 1”,而不是“ 2”。
这是MVC中的错误吗?还是我做错了什么?
更新资料
如果我更换
@Html.HiddenFor(model => model.Id)
与
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="@Model.Id" />
它呈现正确的Id值。
更新2
public async Task<ActionResult> Committees(int id, PrivilegedAction? actionToTake, int? committeeId, ConferenceStatusMessage? csm)
{
Conference conference;
HandleConferenceStatusMessage(csm);
try
{
conference = await db.Conferences
.Include(i => i.Committees.Select(c => c.CommitteeMemberCommitteeEntries))
.Where(i => i.Id == id)
.SingleAsync();
HandleAction(actionToTake, conference);
HandleAuthorisations(conference);
}
catch
{
return ConferenceActionFail();
}
if (committeeId == null)
{
if (conference.Committees.FirstOrDefault() == null)
{
committeeId = 0;
}
else
{
committeeId = conference.Committees.FirstOrDefault().Id;
}
ViewBag.ConferenceId = id; // used for adding a committee member entry
return RedirectToAction("Committees", new { id = id, action = actionToTake, committeeId = committeeId, csm = csm });
}
else
{
if (CommitteeIsPartOfConference(conference, committeeId) || committeeId == 0)
{
ViewBag.SelectedCommittee = committeeId;
ViewBag.JsonAvailableMembers = jsonAvailableCommitteeMembers(id);
return View(conference);
}
else
{
return HttpNotFound();
}
}
}
最佳答案
在返回视图之前尝试使用此方法:
ModelState.Clear();
通常,当调用
Action
时,框架会基于查询字符串值,后数据,路由值等来构建ModelStateCollection
。此ModelStateCollection
将传递给View
。在尝试从实际模型中获取值之前,所有HTML输入帮助程序都首先尝试从ModelStateCollection
获取值。这就是为什么您的
Html.HiddenFor
扩展名无法正常工作(首先检查ModelStateCollection)而您的<input type="hidden">
包含正确值的原因。