【问题标题】:Request.IsAjaxRequest not woking mvcRequest.IsAjaxRequest 不工作 mvc
【发布时间】:2016-07-01 23:49:50
【问题描述】:

当我使用 Request.IsAjaxRequest() 时。我无法返回视图()。请检查下面的代码。 这是行动。

public ActionResult Index()
    {
        if (!Request.IsAjaxRequest()) {
            return View("ajexview");            
        }
        return view("About");
    }

这是视图

<script>
$(function () {
    $("button").click(function () {
        var car = { Make: 'Audi', Model: 'A4 Avant', Color: 'Black', Registered: 2013 };
        $.ajax({
            type: "POST",
            url: "/home/index/",
            data: car,
            datatype: "html",
            success: function (data) {
                $('#result').html(data);
            }
        });
    });
});

<button>Click me</button>

当我发布关于视图时无法返回

【问题讨论】:

  • 您应该在控制器中使用另一个操作来处​​理 ajax 请求。通常,当您发出 ajax 请求时,您会将其指向返回类似 JsonResult 的操作。看一下这个问题的控制器代码:stackoverflow.com/questions/16186083/…

标签: c# ajax model-view-controller


【解决方案1】:

首先,我不确定您的 Index 操作是否会受到您的 ajax 调用的影响。您正在针对获取操作发布帖子。要使 Request.IsAjaxRequest() 按预期工作,请尝试创建另一个控制器操作并使用 HttpPost 属性对其进行标记,如下所示,

[HttpPost]
public ActionResult Index(Car car)
{
   if (!Request.IsAjaxRequest()) {
        return PartialView("ajexview");            
    }
    return View("About");
}

还要注意,在if (!Request.IsAjaxRequest()) 块中,我将“ajexview”作为PartialView 返回。

或者如果您的意图是点击获取索引操作,那么您将需要执行 ajax 'get' 请求,而不是像

$.ajax({
        type: "GET",
        url: "/home/index/",
        success: function (data) {
        $('#result').html(data);
    }
});

【讨论】:

    【解决方案2】:

    确保在 _layout.cshtml 中的正确位置和顺序呈现脚本:

    例如在顶部: ...

        <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    

    ...和底部:

             @Scripts.Render("~/bundles/jquery")
             @Scripts.Render("~/bundles/jqueryval")
             @Scripts.Render("~/bundles/bootstrap")
             @Styles.Render("~/Content/datatables")
             @Scripts.Render("~/bundles/datatables")
             <!-- etc. -->
             @RenderSection("scripts", required: false) 
        </body> 
    </html>
    

    还要注意 BundleConfig.cs 的构造。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多