开发者

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 开发者_StackOverflow社区json type or is there anyway to use the same action for http request (post) and jQuery too?

Thanks


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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜