简体   繁体   中英

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:

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.

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 ?

Following the helpful information I was given by @GSerg, I thought I'd share my resolution.

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.

Then within the Controller, set up the code to return the view as normal (in this case for the Index view)...

[HttpGet]
public ActionResult Index()
{
     return View();
}

Then for the partial views, set up a PartialViewResult for each partial view annotated with ChildActionOnly ...

[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM