Dimas Longo
Dimas Longo

Reputation: 1217

How to get returned data from a controller in AjaxOptions using asp net mvc 4

I have this form

@using (Ajax.BeginForm("opImportFile", "Operacao", new AjaxOptions { HttpMethod = "POST",
OnSuccess = "LimparCampos('true')", OnFailure = "LimparCampos('false')" }, 
new { id = "formUpdStoringSettings" }))
{ ... }

Instead of true or false, I would like to pass a string returned by /Operacao/opImportFile

Is this possible?

Upvotes: 1

Views: 2375

Answers (3)

Andy T
Andy T

Reputation: 9881

Based on the documentation, the callback is being provided with the returned ajax content, which itself has a "get_data() method to get the response from the server".

In your definition, you probably just need to point to the callback method, and not actually call it yourself (meaning, don't include the paramters):

OnSuccess = "LimparCampos"

Upvotes: 1

Shyju
Shyju

Reputation: 218732

I am so inclined to avoid using AjaxForm. I would write the normal form and have my javascript to handle the form posting seperate. Simple and Clean.

@using(Html.Beginform("opImportFile","Operaco"))
{
  //some elements here
  <input type="submit" value="Save" id="btnSave" />
}

And some javascript to make our form submit to ajaxified version

$(function(){
  $("#btnSave").click(function(e){
     var _form=$(this).closest("form");
     e.preventDefault();
     $.post(_form.attr("action"),_form.serialize(),function(response){
         // now response variable has the return item from the action method.
         // and do some fun stuff with that.
         alert(response);

     });
  });
});

You can return anything from your action method. A string, JSON or a partial view.

Upvotes: 1

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

try setting up callback function like this:

OnSuccess = "LimparCampos"

and access the data with :

  function LimparCampos(response) {
     var jsonResult = response.get_response().get_object();

  }

Upvotes: 0

Related Questions