【发布时间】:2017-08-01 07:40:23
【问题描述】:
我是第一次练习MVC asp.net,我正在尝试通过Jquery $.ajax 或$.getJSON 方法从Controller 获取产品列表到View,以下是控制器中的功能:
public ActionResult List()
{
Dictionary<string, List<Product>> dict = new Dictionary<string, List<Product>> {{"pList", PList}};
return Json(dict,JsonRequestBehavior.AllowGet);
}
而ajax函数是:
$(window).load(function () {
$.ajax({
url: '@Url.Action("List", "Product")',
type: "GET",
cache: false,
success: function (data) {
$("#div").append("<table><tr><td>ID</td><td>Name</td><td>Description</td><td>Price</td></tr>");
data.pList.each(function () {
$("#div").append("<tr>");
$(this).each(function () {
$("#div").append("<td>" + $(this).Id() + "</td>");
$("#div").append("<td>" + $(this).Name() + "</td>");
$("#div").append("<td>" + $(this).Description() + "</td>");
$("#div").append("<td>" + $(this).Price() + "</td>");
});
$("#div").append("</tr>");
});
$("#div").append("</table>");
}
});
});
在加载 \Product\List 时,它会在浏览器上呈现 List.json 文件,而不是重定向到 \Product\List 并创建 ajax 成功函数中提供的动态表。我遵循了许多教程,表明这种方法是正确的。
【问题讨论】:
-
调用视图的方法。
-
先返回你的视图,然后使用对象触发AJAX调用(例如
ActionLink或按钮)而不是直接使用$(window).load。 -
谢谢你,它成功了:)
标签: jquery asp.net json ajax asp.net-mvc