如何从 ASP.NET MVC 控制器动态获取数据到 jQuery?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13198136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get data from ASP.NET MVC controller to jQuery dynamically?
提问by Citrus
I have a jQuery function that on the click of a div element, gets that elements predefined ID value. What I want to do is load that parent elements children, so I'm planning to dynamically build some html using jQuery. What I don't know how to do, is make a call to a controller (ASP.NET MVC 3) and have the controller return a collection to the client.
我有一个 jQuery 函数,单击 div 元素即可获取该元素的预定义 ID 值。我想要做的是加载父元素子元素,所以我计划使用 jQuery 动态构建一些 html。我不知道该怎么做,是调用控制器(ASP.NET MVC 3)并让控制器将集合返回给客户端。
I know how to send a JSON object from jQuery to a controller, but not the other way around.
我知道如何将 JSON 对象从 jQuery 发送到控制器,但反过来不行。
Thanks in advance!
提前致谢!
回答by Yasser Shaikh
Here is the code for how you send data from Controller to json:
以下是如何将数据从 Controller 发送到 json 的代码:
$.ajax({
url: '@Url.Action("GetData", "Home")',
type: "GET",
success: function (result) {
$("#somediv").append(result.FirstName);
$("#somediv").append(result.LastName);
$("#somediv").append(result.Age);
}
});
Consider a class like the one below....
考虑一个像下面这样的类......
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
your action should look like this.
你的动作应该是这样的。
public JsonResult GetData()
{
User user = new User();
user.FirstName = "Yasser";
user.LastName = "Shaikh";
user.Age = 100;
return Json(user, JsonRequestBehavior.AllowGet);
}
回答by Kirill Bestemyanov
Sample:
样本:
Javascript:
Javascript:
$.ajax({
type: 'POST',
url: '@(Url.Action("SomeAction", "SomeController"))',
data: someInputData,
error: OnErrorFunction,
success: function (data, textStatus, XMLHttpRequest) {
alert(JSON.stringify(data));
},
dataType: "json"
});
Controller:
控制器:
public ActionResult SomeAction(InputDataType someInputData)
{
if (someInputData== null)
return null;
return new JsonResult {Data = SomeOutputData(someInputData)};
}
回答by Nick
You can make use of the jquery ajax
function and the MVC Razor Url
property:
您可以使用 jqueryajax
函数和 MVC RazorUrl
属性:
$.ajax({
url: '@Url.Action("Home")',
type: "GET",
success: function (data) {
$("my-div").append(data);
}
});
The value of the success property is a function with one argument: data. This is the result of what is returned from your controller.
success 属性的值是一个带有一个参数的函数:data。这是从您的控制器返回的结果。