2

I want to post a form via ajax call also model will be passed into the action method, but want to get Model errors via json. How can I do this?

2 Answers 2

3

You could write a custom action filter:

public class HandleJsonErrors : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var modelState = (filterContext.Controller as Controller).ModelState;
        if (!modelState.IsValid)
        {
            // if the model is not valid prepare some JSON response
            // including the modelstate errors and cancel the execution
            // of the action.
            // TODO: This JSON could be further flattened/simplified
            var errors = modelState
                .Where(x => x.Value.Errors.Count > 0)
                .Select(x => new
                {
                    x.Key,
                    x.Value.Errors
                });
            filterContext.Result = new JsonResult
            {
                Data = new { isvalid = false, errors = errors }
            };
        }
    }
}

and then put it into action.

Model:

public class MyViewModel
{
    [StringLength(10, MinimumLength = 5)]
    public string Foo { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [HandleJsonErrors]
    public ActionResult Index(MyViewModel model)
    {
        // if you get this far the model was valid => process it
        // and return some result
        return Json(new { isvalid = true, success = "ok" });
    }
}

and finally the request:

$.ajax({
    url: '@Url.Action("Index")',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        foo: 'abc'
    }),
    success: function (result) {
        if (!result.isvalid) {
            alert(result.errors[0].Errors[0].ErrorMessage);
        } else {
            alert(result.success);
        }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Darin... great answer. I'm ready to put it into action here. Would you still recommend this approach today with ASP.NET MVC 4 and 5 out the door?
I think this other answer provided by you is a better approach: stackoverflow.com/a/7287646/114029
1

Something like this?

  $.ajax({
                    type: "POST",
                    url: $('#dialogform form').attr("action"),
                    data: $('#dialogform form').serialize(),
                    success: function (data) {
                        if(data.Success){
                          log.info("Successfully saved");
                          window.close();
                        }
                        else {
                          log.error("Save failed");
                          alert(data.ErrorMessage);
                    },
                    error: function(data){
                        alert("Error");
                    }
                });


    [HttpPost]
    public JsonResult SaveServiceReport(Model model)
    {
        try
        {
            //
        }
        catch(Exception ex)
        {
            return Json(new AdminResponse { Success = false, ErrorMessage = "Failed" }, JsonRequestBehavior.AllowGet);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.