MVC 3 - Ajax.BeginForm完整回发

时间:2011-02-21 00:04:37

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

在下面的代码中,我使用Ajax.BeginForm异步发布数据到操作。调用该操作但结果将显示到新的网页。我看了很多例子。这似乎并不困难。我已经使这个例子非常简单地用于概念证明(poc),但我仍然看到一个新的页面显示。

控制器

  [HttpPost]
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public string TestAjax(UserViewModel viewModel)
    {

        return viewModel.UserName;
    }

查看

@model BasicMvc3Example2.Models.UserViewModel

@{
    ViewBag.Title = "Index2";
    Layout = null;//"~/Views/Shared/_Layout.cshtml";
}

      <script src="/BasicMvc3Example2/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
    <script src="/BasicMvc3Example2/Scripts/jquery-ui.js" type="text/javascript"></script>
    <script src="/BasicMvc3Example2/Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="/BasicMvc3Example2/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
    <h2>Index2</h2>

    <script type="text/javascript">
        function PostFailure(){
            alert("Failure");
        }

        function PostSuccess(){
            alert("Success");
        }

        function PostOnComplete() {
            alert("Complete");
        }
    </script>

    Page Rendered: @DateTime.Now.ToLongTimeString()
    @using (Ajax.BeginForm("TestAjax", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "textEntered", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }))
    {
        <div>
           @Html.LabelFor(m => m.UserName)
           @Html.TextBoxFor(m => m.UserName)
        </div>

        <div>
           @Html.LabelFor(m => m.Password)
           @Html.TextBoxFor(m => m.Password)
        </div>

        <div>
           @Html.LabelFor(m => m.EmailAddress)
           @Html.TextBoxFor(m => m.EmailAddress)
        </div>

        <input type="submit" id="submitForm" value="Submit Form" />
    }

    <div id="textEntered">d</div>

2 个答案:

答案 0 :(得分:66)

您可以查看_Layout.cshtml并确保引用了ajax脚本吗?我不认为它是默认的:

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

答案 1 :(得分:15)

另请记住,您需要在webconfig

中使用此功能
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
相关问题