Receive JSON data within OnComplete event function in Ajax.Beginform
.net, ajax, asp.net-mvc-3, json
Solution
The explanation that gains best interpretation for us could be that:
When we use OnComplete and JSON, the response is embedded directly to the DOM of the page. For that purposes instead it's recommended using OnSuccess and OnFailure. Those actually handle perfectly JSON results coming from a controller action.
I remit you guys to The link that helped me, that was the same I ignored previously, which I continued reading and found the Joel Purra's answer.
In your Ajax.BeginForm:
new AjaxOptions
{
**OnFailure** = "onTestFailure",
**OnSuccess** = "onTestSuccess"
}
Script block:
<script>
//<![CDATA[
function onTestFailure(xhr, status, error) {
console.log("xhr", xhr);
console.log("status", status);
// TODO: make me pretty
alert(error);
}
function onTestSuccess(data, status, xhr) {
console.log("data", data);
console.log("status", status);
console.log("xhr", xhr);
// Here's where you use the JSON object
//doSomethingUseful(data);
}
Problem
I'm trying to use Ajax.BeginForm features. The form is posted correctly, but I need to retrieve data in json format, from my controller action and refresh a div with the operation result message. I have found several suggestions here in Stackoverflow, but none is useful. Here is a suggestion found: ``` var data = content.get_response().get_object(); ``` But it didn't work for me. And I believe is deprecated up today, functional only for MVC 2 and lower versions. My current MVC version is 3. Here is a piece of code: ``` <script type="text/javascript"> function fnCompleted(data){ if(data.Success) $("#somediv").html(data.StatusMessage).addClass("success"); else $("#somediv").html(data.StatusMessage).addClass("error"); } </script> @{ var ajaxOptions= new AjaxOptions{ OnComplete= "fnCompleted", Url= '@Url.Action("myAction", "myController")', Method= "POST" } <div id="somediv">/*Here goes the json response*/</div> using(Ajax.BeginForm(ajaxOptions)){ @Html.EditorForModel() <input type="submit" name="send" value="Send"> ``` } Here is a piece of my controller action: ``` [HttpPost] public JsonResult myAction(MyModel mymodel) { try { if (myModel== null) throw new Exception("The model is empty"); if (!ModelState.IsValid) throw new Exception("The model is wrong"); var found = /*Look for existence of the model in the database*/; if(found) throw new Exception("Already exists the object"); /*Operation with the database*/ var result = Json( new { Success = true,//success StatusMessage = "Object created successfully" }); return result; } catch (Exception exception) { var result = Json( new { Success = false,//error StatusMessage = exception.Message }); return result; } } ```