PageMethods with ASP.Net MVC

余生长醉 提交于 2019-12-01 18:03:43

问题


I have found ASP.Net PageMethods very handy and easy to use, but I have just started developing using MVC and am not sure how to use them?

What is the equivalent of PageMethods.MyFunction() in MVC where MyFunction is a Controller action?

I know I can use the Json function to return a value, but how do I call the action from the client?


回答1:


I know I can use the Json function to return a value, but how do I call the action from the client?

I think you're looking for either getJSON

$.getJSON("/controller/action", function(json)
{
  alert("JSON Data: " + json.users[3].name);
});

or the ajax jQuery method.

Either can call an action and get JSON data back from ASP.NET MVC very easily.




回答2:


I don't think you need page methods. Page methods in asp.net are a way to expose methods in the page class to your client-side code.

In MVC, you don't have a page class, so you can just issue an XHR to a url (../controller/action/params, or whatever), and return JSON from the action.

Update: After re-reading your question, it sounds like you want to know how to issue an XHR from the client. In raw javascript, you can just use the XMLHttpRequest object, but whatever JS library you are using probably has a nicer wrapper. jQuery's, for instance, is here



来源:https://stackoverflow.com/questions/369595/pagemethods-with-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!