我是 ASP.NET MVC(-4) 的新手。
我想使用 jquery 从我的网站进行 Ajax 调用,并使用返回的 html 在页面上填充一个 div。因为它只是一个 div,所以我不需要带有标题和完整正文等内容的完整 html 页面。
接收方应该是什么?
它应该是普通 View 、局部 View 、某种特殊类型的资源或处理程序还是某种其他魔法?
最佳答案
您可以使用此 With Post 和 Get 操作
脚本
$.ajax({
url: '@Url.Action("SomeView")',
type: 'GET',
cache: false,
data: { some_id: id},
success: function(result) {
$('#container').html(result);
}
});
Controller
public ActionResult SomeView(int some_id)
{
....
return PartialView();
}
查看
<div id="container">
@Html.Partial("SomeViewPartial")
</div>
或者您可以使用 AjaxActionLink
查看
@Ajax.ActionLink("text", "action", "controller",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "container",
OnSuccess = "onSuccess",
})
脚本
function onSuccess(result) {
alert(result.foo);
}
Controller
public ActionResult SomeView(int some_id)
{
return Json(new { foo = "bar" }, JsonRequestBehavior.AllowGet);
}
另外 您可以使用 Ajax.ActionLink 仅更新内容页面。使用这个:
在 ~/Views/ViewStart.cshtml:
@{
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}
关于ajax - ASP.NET MVC-4 : What should receive an ajax call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12093552/