无法使用AJAX以最简单的方式发布异步ASP.NET MVC3表单

时间:2011-05-24 04:47:38

标签: asp.net-mvc asp.net-mvc-3 razor

我无法理解为什么以下表单执行完整回发而不是使用AJAX异步回发。 Request.IsAjaxRequest()总是假的。我想我已经正确地遵循了所有的例子。我做错了什么?

以下是观点:

@(Layout = null)
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>    
</head>
<body>
    <div>
        <div id="update"></div>
        @using(Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update" }))
        {
            <input type="submit" value="test" />
        }
    </div>
</body>
</html>

这是控制器:

using System.Web.Mvc;

namespace TheHoges.Web.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
            {
                // never gets here
                return Content("it worked");
            }
            return View();
        }
    }

}

1 个答案:

答案 0 :(得分:2)

供参考:

AJAX and MVC 3

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

你在web.config中看到这个吗?

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

如果,是的,包括上面的库可以解决您的问题。

为了彻底,我创建了一个测试页面。工作桃子......

    @{
    ViewBag.Title = "Home Page";
}

@(Layout = null)
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
</head>
<body>
    <div>
            <div id="update">
            </div>    
        @using(Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update" }))
        {                       
            <input type="submit" value="test" />
        }
    </div>
</body>
</html>