0

I have a MVC project, on one page, when clicked a link, it pops a modal dialog which has some buttons on it. One button is for adding a new user. If there is ModelState error, it should show the error in the Modal Dialog. How can I do that?

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddNewUser(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        ......
    }

    // If we got this far, something failed, redisplay form in Modal Dialog
    // what should return here?
}

I searched, it seems we have to make a ajax call to validate the ModelState.

Is there any other ways instead of this? Thanks

urlreader
  • 6,319
  • 7
  • 57
  • 91
  • You may return a view result (return View()) in which you may render the validation errors using the validation helpers. You probably want to make the form (inside your modal dialog) to do an ajax form submit. – Shyju Jan 14 '18 at 23:25
  • This post might give you some ideas [When model is not valid, return to partial view inside a view, with error message using asp.net core](https://stackoverflow.com/questions/47099687/when-model-is-not-valid-return-to-partial-view-inside-a-view-with-error-messag) – Shyju Jan 14 '18 at 23:29
  • If you do not want ajax, then you would need to return the original view (including the html for the popup) and a flag to indicate the modal should be visible –  Jan 14 '18 at 23:32
  • if that's the case, maybe ajax is the best choice. just curious, no other simple way? – urlreader Jan 15 '18 at 00:30
  • Ajax is certainly the simplest. And you have the option of returning a `JsonResult` containing the property names and associated error messages (and update the DOM with it) rather than the whole view to improve performance further. –  Jan 15 '18 at 02:32
  • If you do return a view, then you must also reparse the `$.validator` if you have enabled client side validation (refer [Required field validations not working in JQuery Popup MVC 4](https://stackoverflow.com/questions/31768946/required-field-validations-not-working-in-jquery-popup-mvc-4/31769058#31769058) for an example) –  Jan 15 '18 at 02:33

0 Answers0