加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

为什么Request.IsAjaxRequest()在ASP.NET MVC 3中不起作用?

发布时间:2020-12-16 06:37:04 所属栏目:asp.Net 来源:网络整理
导读:我正在使用Razor创建一个新项目asp.net mvc3,并希望将LogOn转换为ajax请求. HTML @using (Ajax.BeginForm("LogOn","Account",new AjaxOptions { HttpMethod="post",OnSuccess="LoginSubmitted"})){} 调节器 if (Request.IsAjaxRequest()){ return Json(new {
我正在使用Razor创建一个新项目asp.net mvc3,并希望将LogOn转换为ajax请求.

HTML

@using (Ajax.BeginForm("LogOn","Account",new AjaxOptions { HttpMethod="post",OnSuccess="LoginSubmitted"}))
{
}

调节器

if (Request.IsAjaxRequest())
{
    return Json(new { ResultMessage = "Username or password provided is incorrect"});
}
else
{
    ModelState.AddModelError("","The user name or password provided is incorrect.");
}

其他一切都是一样的.

首先,看着Fiddler的http响应,我注意到没有x-requested-with标头.所以我补充一下

<input type="hidden" name="X-Requested-With" value="XMLHttpRequest" />

这似乎工作,但现在我收到的是一个Json对象,它没有被解析,而谷歌Chrome只是通过发回一个应用程序/ json文档将Json渲染到屏幕.所有脚本都已到位.

我也这样做了:

@using (Ajax.BeginForm("Submit","home",new AjaxOptions { HttpMethod = "Post",OnSuccess="LoginSubmitted"}))
{
}


@section head
{
    <script type="text/javascript">
        function LoginSubmitted(res) {
            alert(res.Message);
        }   
    </script>
}


    public ActionResult Submit(string id)
    {
        if (Request.IsAjaxRequest())
        {
            return Json(new { Message = "Logged In" } );
        }
        else
        {
            return View();
        }
    }

以我自己创建的形式,使用标准助手可以正常工作.

发生了什么?

解决方法

那是因为默认情况下ASP.NET MVC 3使用jQuery和不引人注目的AJAX而不是MicrosoftAjax *库.这意味着当您编写Ajax.BeginForm时,您需要在页面中包含正确的脚本:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

并在您的web.config中确保您启用了不显眼的JavaScript:

<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

现在,您可以安全地丢弃页面上的所有MicrosoftAjax *脚本引用(如果有的话),它们将不再使用.

据我个人说,我从来没有使用任何Ajax.*助手.我总是喜欢控制.所以我会写:

@using (Html.BeginForm("LogOn","Account"))
{
}

然后使用jquery form plugin AJAXify此表单:

$(function() {
    $('form').ajaxForm(function(result) {
        alert('form successfully submitted');
    });
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读