MVC 3 - Ajax.BeginForm does a full post back

2019-01-14 20:19发布

问题:

In the following code, I'm using Ajax.BeginForm to post data to the action asynchronously. The action gets called but the results are displayed to a new web page. I'v looked at a ton of example. This doesn't seem difficult. I've made the example extremely simple for a proof of concept (poc), but I'm still seeing a new page displayed.

Controller

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

        return viewModel.UserName;
    }

View

@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>

回答1:

Can you check _Layout.cshtml and make sure the ajax script is referenced? I don't think it is by default:

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


回答2:

Also remember that you need this in the webconfig

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