Receive JSON data in OnComplete event function in Ajax.Beginform

I am trying to use the Ajax.BeginForm functions.

The form is submitting correctly, but I need to get json data from my controller action and update the div message with the result of the operation.

I found some suggestions here on Stackoverflow but none are helpful.

Here's a suggestion:

var data = content.get_response().get_object();

      

But that didn't work for me . And I believe it is outdated today, functional only for MVC 2 and lower versions. My current version is MVC 3 .

Here's a snippet 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 portion 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;
        }
   }

      

+3


source to share


2 answers


The explanation that works best for us might be as follows:

When we use OnComplete and JSON, the response is embedded directly into the page's DOM. It is recommended to use OnSuccess and OnFailure instead. In fact, they handle JSON results well from the controller action.

I pass you guys in the link that helped me, it was the same thing I ignored earlier , which I kept reading and found 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 where you use the JSON object
    //doSomethingUseful(data);
}

      

+6


source


Is there a way to store the result in the view of the OnComplete JS function?

Of course, there are several ways to store the data received by the controller. I can suggest you to use a client model similar to the backbone.js model.

By using the backbone.js model, you can store properly formatted JSON objects and collections of JSON data on the client side.



Another way is to use a hidden browser variable. A small amount of data can be stored in hidden input management.

And another way is to use session based cookie.

Edit: If client side MVC like backbone.js might need to revisit your current view. But in the long run, I think it's beneficial.

0


source







All Articles