Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display ModelState error returned by JsonResult in MVC 3 project?

I have a create page that uses a JsonResult action instead of ActionResult. In the ActionResult action, the errors are displayed on the view beside the offending field. Right now the JsonResult only returns a string that is displayed in an alert box.

Can I display the ModelState errors on the view?

The controller

[HttpPost]
public JsonResult Create(Tload tload)
    {
        if (ModelState.IsValid)
        {                
          ...save changes
            return Json(new { Success = 1, TransloadID = transload.TransloadID, ex = "" });
        }
        else
        {
        string totalError = "";
        foreach (var obj in ModelState.Values)
        {
            foreach (var error in obj.Errors)
            {
                if (!string.IsNullOrEmpty(error.ErrorMessage))
                {
                    totalError = totalError + error.ErrorMessage + Environment.NewLine;
                }
            }
        } 

        return Json(new { Success = 0, ex = new Exception(totalError).Message.ToString()});
    }

jquery/javascript code in view

function Save() {
        // Step 1: Read View Data and Create JSON Object
...do stuff here
        // Set 2: Ajax Post
        // Here i have used ajax post for saving/updating information
        $.ajax({
            url: '/Expedite/Create',
            data: JSON.stringify(salesmain),
            type: 'POST',
            contentType: 'application/json;',
            dataType: 'json',
            success: function (result) {

                if (result.Success == "1") {
                    window.location.href = "/Expedite/index";
                }
                else {
                    alert(result.ex);
                }
            }
        });


    }
like image 567
John M Avatar asked Nov 14 '22 06:11

John M


1 Answers

have a placeholder for the error and hide it initially

<div id="err"></div>

and when errors are raised

else {
       $("#err").html(result.ex);
       $("#err").show();
       //or you can use .slideDown() etc            
}
like image 193
Rafay Avatar answered Jan 21 '23 09:01

Rafay