user2783193
user2783193

Reputation: 1012

manage serverside validaton when I use jquery post

From razor view I'm sending js object using jquery to the mvc controller. Reason why I do it using jquery post method and not razors form is that I need to manage dynamic input of certain fields. On the view certain fields (inputtextbox) are dynamically added to the view (from 0 - 10) and I manage that solution using js on the page.

 var myJsObj = ...
 $.ajax({
           type: 'POST',
           traditional: true,
           contentType: 'application/json',
           url: '/MyController/SomeAction',
           data: JSON.stringify({ model: myJsObj}),
           success: function () {

           }
 });

On the server side, mvc receives that model and in case of some error I want to return this object back to the view.

[HttpPost]
public ActionResult SomeAction(MyModel model)
{
   if(!ModelState.IsValid)
   {
      ModelState.AddModelError("", "Error occured!");
      return View(model);
   }     
   return RedirectToAction("Index");  
}

I have inside razor view

Html.ValidationSummary

but since I'm using jquery post I dont know how to receive back to the view and display error like I would use regular razor form. Or if you know better approach to manage dynamically added input boxes on the razor view please post. Any help please.

Upvotes: 1

Views: 73

Answers (2)

Rajeev Goel
Rajeev Goel

Reputation: 1523

I think you've got a couple of options here:

  1. If you prefer to continue to use an Ajax POST as you've shown above, then you need to take the response from the POST and inject it back into your current HTML document. For example,

$.ajax({
       type: 'POST',
       traditional: true,
       contentType: 'application/json',
       url: '/MyController/SomeAction',
       data: JSON.stringify({ model: myJsObj}),
       success: function (data) {
           // This is the case where the MVC action found model validation
           // errors, and so it is responding with an HTML document that 
           // shows the errors.
           var returnedBodyHtml = $(data).find('body').html();
           $('body').html(returnedBodyHtml);
       }
     });

(That's untested code up there, so you may have to debug a little bit.) But this code doesn't handle the case where the server responded with a redirect (in the case of successful validation). So, check out this post for some options there.

  1. Your other option is to use the standard Form submit. I know you said you had some dynamically generated input controls on your page, but that doesn't mean that you can't do a Form submit. You just need to make sure that these dynamically generated elements have the correct "name" attribute on them, so that their values get mapped appropriately to the Model on the server side action that is accepting the POST. For example, if your Javascript is dynamically generating an HTML element like this, and inserting it into the form:

<input type="text" name="myDynamicallyGeneratedInput[0]" />
<input type="text" name="myDynamicallyGeneratedInput[1]" />
<input type="text" name="myDynamicallyGeneratedInput[2]" />
<input type="text" name="myDynamicallyGeneratedInput[3]" />

then your Form submit will still work, as long as on the server side, your MyModel class has that corresponding property:

class MyModel
{
    public List<string> MyDynamicallyGeneratedInput {get; set;}
}

Upvotes: 1

kryptonkal
kryptonkal

Reputation: 894

This is what I have done to display errors for dynamic inputs. First off, take a look at this post to give you a better understanding. I have modified my code to better suit my needs, but you can check if it works for your application. use-asp-net-mvc-validation-with-jquery-ajax. I would then consume the return result in the ajax post error callback. It returns a code 400 'Bad Request' on validation errors. The validator variable is the form validator object.

error: function (xhr, textStatus, errorThrown) {
     var statusCode = parseInt(xhr.status);
     if (statusCode == 400) {
         var data = $.parseJSON(xhr.responseText);
         var message = "";
         $.each(data, function (i, item) {
             var propertyName = "" + item.key + "";
             if ($("input[name='" + item.key + "']").length > 0) {
                 var errorObj = {};
                 errorObj[item.key] = item.error;
                 validator.showErrors(errorObj);
            }
            else {
                message += "<div>" + item.key + ": " + item.error + "</div>";
            }
        });

        if (message != "") {
            //display message
         }
    }
}

I hope this helps. Good luck.

Upvotes: 1

Related Questions