Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Although sending back a response and checking the data object in the callback (as explained above by @Richard and @Jatin) will work, I tend to follow the following pattern of rolling my own AjaxResult object, hydrating this object with the model state validity, the success state, as well as any data I need to pass back to the $.ajax success callback function. This enables a flexible and elegant solution in handling $.ajax requests. For example:</p> <pre><code>// custom ajax request result class public class AjaxResult { public bool IsValid { get; set; } public bool Success { get; set; } public string Message { get; set; } public Dictionary&lt;string, object&gt; Data { get; set; } public AjaxResult() { Data = new Dictionary&lt;string, object&gt;(); } public void AddData(string dataKey, object dataValue) { if (dataKey != null &amp;&amp; !Data.ContainsKey(dataKey)) { Data.Add(dataKey, dataValue); } } } // controller public ActionResult NhpdAdminRejectAddress(NhpdAdminViewModel model) { AjaxResult result = new AjaxResult(); if (ModelState.IsValid) { // do something result.AddData("Code", -1); result.IsValid = true; result.Success = true; } return Json(result); } // ajax post request $.ajax({ type: "POST", url: '@Url.Action("NHPDAdminRejectAddress", "Home")', data: JSON.stringify(model), contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { if (result != null &amp;&amp; result.Data != null &amp;&amp; result.Data.Code != null) { int code = result.Data.Code; } }, error: function () { // handle error } }); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload