SC.Cee
SC.Cee

Reputation: 237

.Net Core Server Side Model Validation via unobtrusive ajax form

I have a View that uses unobtrusive ajax to submit a form or rather just normal jquery ajax would do the trick as well. For both implementations, I can get it to hit my controller fine and does my ModelState.IsValid validation and then returns my view like so:

public ActionResult SubmitForm(ViewModel viewModel) 
{ 
    if(!ModelState.IsValid) 
    {
        return View("~/view path", viewModel); 
    }else 
    {
        // do stuff
        // I have to return this in order for me to get my model validation errors to show up
        return Json(new { msg = "OK" }); 
    }
}

View:

<form asp-action="SubmitForm" asp-controller="Controller" data-ajax="true" data-ajax-method="POST"
      data-ajax-success="onSubmitSuccess(data, 'formId')" id="formId">
      
      @Html.ValidationSummary()
      // some form fields with html tag helpers
</form>

Now when my SubmitForm action returns my view on failed model validation, my validation summary never shows up. The only way I've got it to work is by replacing my whole forms html with my returned data like so in my OnSubmitSuccess function by checking the json msg property:

function onSubmitSuccess(data, form) 
{
    if(data.msg) 
    {
        if(data.msg == "OK") { // do stuff }
    }else 
    {
        $("#" + form).html(data.responseText);
    }
}

I'm basically replacing my forms html with the incoming response text in order for my error messages to show up. Is there a particular reason why I can't just do a return Partial or return View and work without tinkering with jquery and replacing html?

Thanks

Upvotes: 0

Views: 461

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 28067

As far as I know, the data-ajax-success require the function which will contains three parameters data, status, xhr, we couldn't pass the formid as the parameter to the data-ajax-success function.

Besides, if you want to pass the partival view as the returned result to the client side, you should directly use data instead of the data.responseText to show the view content value.

More details, you could refer to below test demo and codes:

@model DotNet5Identity.Models.GetInTouch
@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>


<form asp-action="SubmitForm" asp-controller="GetInTouch" data-ajax="true" data-ajax-method="POST"
      data-ajax-success="completed" id="formId">

    <input asp-for="Id" />
    <br />
    <input asp-for="EmailAddress" />

    <input type="submit" value="Tst" />

    @Html.ValidationSummary()
    // some form fields with html tag helpers
</form>


@section scripts{

    <partial name="_ValidationScriptsPartial" />
    <script>
        completed = function (data, status, xhr) {
            alert(data.msg);

         
                if (data.msg == "OK") {

                } else {
                    $("#formId").html(data);
                }
            
        };
 

    </script>


}

Controller:

    public ActionResult SubmitForm(GetInTouch viewModel)
    {

        return PartialView("_TestPartialView");
       
            // do stuff
            // I have to return this in order for me to get my model validation errors to show up
            return Json(new { msg = "OK" });
        
    }

Result:

enter image description here

Upvotes: 0

Related Questions