ajax - ASP.NET MVC-4 : What should receive an ajax call

标签 ajax asp.net-mvc asp.net-mvc-4

我是 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/

相关文章:

javascript - AJAX 与 FOR 循环 JS

javascript - 将 History.js 与 mod_rewriting URL 一起使用

jquery - 为什么我的 jquery.ajax() 函数在上传到实时服务器时显示 'Aborted'

c# - 解析器错误消息 : Could not load type 'ObamPortal.Web.MvcApplication'

asp.net-mvc-4 - 自定义 IActionInvoker 和异步操作

javascript - 刷新某个div

c# - 为什么 JSON 空字符串在服务器端反序列化为 null?

c# - 从表中获取最大值,除非为空

c# - 时间选择器保存 12 小时至 24 小时格式

asp.net-mvc-4 - 我可以向 ApiController 添加操作作为扩展方法吗?