表单validation失败时,将错过查询字符串参数
我有一个包含以下url的表单:CreateEntity? officeCodeId = 5
当我发送表单进行validation并且validation失败时,它只返回CreateEntity url。 没有officeCodeId = 5。
如果用户点击URL或F5上的输入 – 我的网站失败 – 它需要丢失officecodeId参数。 我可以将它保存到会话或其他存储中。 但是我希望在URL中有它
我的看法:
[HttpGet] public virtual ActionResult CreateEntity(int? officeCodeId) { var model = new CreateViewModel(); FillViewModel(model, officeCodeId); return View("Create", model); } [HttpPost] protected virtual ActionResult CreateEntity(TEditViewModel model) { if (ModelState.IsValid) { //Do some model stuff if } return View("Create", model); }
编辑。 我的看法:
using (Html.BeginForm("CreateEntity", "Employee", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.HiddenFor(x => x.OfficeCodeId) @Html.LabelFor(model => model.FirstName, CommonRes.FirstNameCol) @Html.TextBoxFor(model => model.FirstName, Model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) @Html.LabelFor(model => model.LastName, CommonRes.LastNameCol) @Html.TextBoxFor(model => model.LastName, Model.LastName) @Html.ValidationMessageFor(model => model.LastName)
}
编辑2.添加:
@using (Html.BeginForm("CreateEntity", "Employee", FormMethod.Post, new { officeCodeId = Model.OfficeCodeId, enctype = "multipart/form-data" }))
避风港帮忙。 它产生以下forms:
解决方案是
问题是您的HttpPost
操作没有任何id
参数的概念。 如果您想支持类似的URL,请使操作签名支持该参数,例如
[HttpGet] public ActionResult CreateEntity(int? officeCodeId) [HttpPost] public ActionResult CreateEntity(int officeCodeId, EditViewModel model);
你的行为应该是这样的:
操作:
[HttpGet] public virtual ActionResult CreateEntity(int? officeCodeId) { var model = new CreateViewModel(); FillViewModel(model, officeCodeId); return View("Create", model); } [HttpPost] public virtual ActionResult CreateEntity(ViewModel model) { if (model.IsValid) { // save... return RedirectToAction("EditEntity", newId!!!); } return View("Create", model); }
HTML:
@using (Html.BeginForm()) { @Html.HiddenFieldFor(m => Model.officeCodeId) ... }
你的officeId应该是模特儿 。 在html表单上,您可以将其存储在隐藏字段中。
你的最终答案非常好并且效果很好,尽管你可以通过简单地包含Request.QueryString
来进一步增强它以使其更通用:
然后使用POST
操作:
[HttpPost] protected virtual ActionResult CreateEntity(TEditViewModel model) { if (!ModelState.IsValid) { return View(model); }
- 如何在MVC 4.0中的View页面上遍历两个viewbag项目
- 将ASP.NET MVC Controller属性注入服务层依赖项?
- 使用entity framework而不使用语句的缺点?
- ConnectionString属性尚未在update-database上初始化
- 格式化DateTime错误“模板只能用于字段访问,属性访问,单维数组索引..”
- 使用await Task async挂起MVC应用程序中的控制器
- 没有密码的ASP.NET MVC Identity登录
- 删除ASP.Net核心dependency injection中的服务
- ASP.NET MVCunit testing自定义AuthorizeAttribute