1

I've a quick question. To call an action through jQuery (to use AJAX), do i have to create a new Action returning json type or is there anyway to use the same action for http request (post) and jQuery too?

Thanks

Gui
  • 9,555
  • 10
  • 42
  • 54

2 Answers2

4

It depends on what you want to do with the data returned.

Say, your actions returns Html, using jQuery, you can put the html returned from the server:

$.ajax('/url/', function(data){
    $('#elementID').html(data);
})

Alternatively, you can use the jQuery .load() method:

$('#elementID').load('/url');

If your action returns a redirect, and you want the client page to redirect to a url, then yes, you need to create a new action that will return Json:

public JsonResult SomeAction()
{
    return Json(new {redirect = true, url = "/Path/ToRedirect"});
}

And using jQuery:

$.ajax('/url/', function(data){
    if(data.redirect) {
        window.location = data.url;
    };
})
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
0

You can use the same action:

$.post(
    '/controller/action', 
    { field_a: "Value a", field_b: "Value b" }, 
    function(data) {
        $('#result').html(data);
    }
);

With ajax, you usually want partial views or json as a return value. With regular post, full html page. Why do you want to use the same action in ajax and regular post?

LukLed
  • 31,452
  • 17
  • 82
  • 107
  • Thanks. I'm now using the Request.IsIsAjaxRequest()) to see if i return a View or other values. – Gui Feb 13 '11 at 03:35
  • Because i just need to return a string, and i want to first call it from javascript. If javascript is disabled, then i use the form. – Gui Feb 13 '11 at 03:41