Gui
Gui

Reputation: 9823

ASP.NET MVC - Calling an Action through jQuery

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

Upvotes: 1

Views: 4200

Answers (2)

LukLed
LukLed

Reputation: 31892

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?

Upvotes: 0

The Scrum Meister
The Scrum Meister

Reputation: 30141

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;
    };
})

Upvotes: 4

Related Questions