【问题标题】:MVC 3 - Ajax.BeginForm does a full post backMVC 3 - Ajax.BeginForm 做一个完整的回帖
【发布时间】:2011-02-21 00:04:36
【问题描述】:

在以下代码中,我使用 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>

【问题讨论】:

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


    【解决方案1】:

    您能否检查_Layout.cshtml 并确保引用了ajax 脚本?我不认为它是默认的:

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

    【讨论】:

    • 感谢您的解决方案。我已经为此奋斗了一天多。该参考不在布局页面中,因此我将其添加到视图中。它现在似乎起作用了。另外,你能告诉我我不需要哪些脚本吗?再次感谢
    • 好吧,我删除了除 jquery.unobtrusive-ajax.js 之外的所有脚本,一切似乎仍然正常。
    • @BarDev,对于 ajax,我认为这是您需要的唯一脚本。如果您最终使用其他功能(如验证),那么您当时需要对这些脚本的引用。
    • 这个答案也适用于MVC4,正如我刚刚经历的那样!
    • 成功了,但是为什么呢?它会忽略部分中的“@section Scripts”吗?
    【解决方案2】:

    还要记住,您需要在 webconfig 中使用它

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

    【讨论】:

      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 2016-09-17
      • 1970-01-01
      相关资源
      最近更新 更多