English 中文(简体)
ASP.NET MVC-通过jQuery调用操作
原标题: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?

谢谢

最佳回答

这取决于您想对返回的数据做什么。

比方说,您的操作返回Html,使用jQuery,您可以将从服务器返回的Html放入:

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

或者,您可以使用jQuery.load()方法:

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

如果您的操作返回重定向,并且您希望客户端页面重定向到url,那么是的,您需要创建一个新的操作,该操作将返回Json:

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

使用jQuery:

$.ajax( /url/ , function(data){
    if(data.redirect) {
        window.location = data.url;
    };
})
问题回答

您可以使用相同的操作:

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

对于ajax,您通常希望部分视图json作为返回值。使用常规帖子完整的html页面。为什么要在ajax和常规post中使用相同的操作?





相关问题
WebForms and ASP.NET MVC co-existence

I am trying to make a WebForms project and ASP.NET MVC per this question. One of the things I ve done to make that happen is that I added a namespaces node to the WebForms web.config: <pages ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

Create an incremental placeholder in NHaml

What I want to reach is a way to add a script and style placeholder in my master. They will include my initial site.css and jquery.js files. Each haml page or partial can then add their own required ...

asp.net mvc automapper parsing

let s say we have something like this public class Person { public string Name {get; set;} public Country Country {get; set;} } public class PersonViewModel { public Person Person {get; ...

structureMap mocks stub help

I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor)...

ASP.NET MVC: How should it work with subversion?

So, I have an asp.net mvc app that is being worked on by multiple developers in differing capacities. This is our first time working on a mvc app and my first time working with .NET. Our app does not ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

热门标签