[英]ASP.Net MVC Using AddModelError with multiple ValidationSummary for querystring validation
I have a view with two forms each containing their own 我有一个包含两种形式的视图
@Html.ValidationSummary()
When the page is loaded, a querystring parameter is checked and if it exists I call: 加载页面后,将检查querystring参数,如果存在,则调用:
ModelState.AddModelError("", "Querystring error");
However, this results in the error message appearing in both @Html.ValidationSummary()
even if I specify a property in the form model. 但是,即使我在表单模型中指定属性,这也会导致错误消息同时出现在
@Html.ValidationSummary()
中。
I have a work around which is to have a seperate error message property in the model for the form and populate that and then display it if it exists in a label, but wondered if it is possible to specify one individual @Html.ValidationSummary()
within a form to allow me to use ModelState.AddModelError
? 我有一个解决方法,就是在模型的表单中有一个单独的错误消息属性,并填充该错误消息属性,然后显示它是否存在于标签中,但是想知道是否可以指定一个单独的
@Html.ValidationSummary()
在表格中允许我使用ModelState.AddModelError
吗?
Following the helpful information I was given by @GSerg, I thought I'd share my resolution. 遵循@GSerg提供的有用信息后,我认为我会分享自己的解决方案。
So instead of having two forms within the same view, I split each form into two separate partial views and called each from within the main view... 因此,我将每个表单分成两个单独的局部视图,而不是在同一个视图中包含两个表单,然后从主视图中调用每个表单...
@Html.Action("_RequestPartial")
@Html.Action("_LoginPartial")
Each partial view would contain the model to pass to it and a Html.BeginForm
with a Html.ValidationSummary()
inside. 每个局部视图都将包含要传递给它的模型,以及一个内部带有
Html.ValidationSummary()
的Html.BeginForm
。
Then within the Controller, set up the code to return the view as normal (in this case for the Index view)... 然后在Controller中,设置代码以正常返回视图(在这种情况下为Index视图)...
[HttpGet]
public ActionResult Index()
{
return View();
}
Then for the partial views, set up a PartialViewResult
for each partial view annotated with ChildActionOnly
... 然后对于部分视图,为每个带有
ChildActionOnly
注释的部分视图设置PartialViewResult
。
[ChildActionOnly]
public PartialViewResult _RequestPartial()
{
... code that populates model you want to pass ...
return PartialView(model);
}
[ChildActionOnly]
public PartialViewResult _LoginPartial()
{
... code that populates model you want to pass ...
return PartialView(model);
}
Hope this helps someone. 希望这对某人有帮助。
To show the specific validation message, please see the snippet code below. 要显示特定的验证消息,请参见下面的代码段。 Controller :
控制器:
[HttpGet]
public ActionResult Index()
{
ModelState.AddModelError("Error1", "Querystring error");
return View(new SampleViewModel());
}
View : 查看:
@Html.ValidationMessage("Error1")
Just tried to create a fiddle to get a complete picture. 只是试图创建一个小提琴以获得完整的图片。 https://dotnetfiddle.net/GoMMhy
https://dotnetfiddle.net/GoMMhy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.