Ajax.BeginForm driving me crazy

2019-04-02 13:58发布

问题:

ASP.NET MVC3

I have a partial view that is initially rendered inside a div. The following is the partial code:

@model Venue.Models.Validation.CustomerRequestModel

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

<script type="text/javascript" src="/Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/Scripts/MicrosoftMvcAjax.js"></script>
<script type="text/javascript" src="/Scripts/MicrosoftMvcValidation.js"></script>

@{ Html.RenderPartial("Message"); }
@Html.ValidationSummary()

@using (Ajax.BeginForm(
            "Customer",
            "Service",
            null,
            new AjaxOptions()
            {
                HttpMethod = "post",
                InsertionMode = InsertionMode.Replace,
                LoadingElementDuration = 100,
                LoadingElementId = "loading-customer",
                OnBegin = "hideSubmitButton",
                OnSuccess = "hideForm",
                OnComplete = "showSubmitButton",
                OnFailure = "showErrorMessage",
                UpdateTargetId = "formclientes",
            },
            new
            {
                id = "customer-form"
            }))
{
    // Fields are all type="text" although some are numbers.
    <input type="text" name="Address" class="clientes_form" />
}

The action:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Customer(CustomerRequestModel customer)
{
  // ...
}

In the immediate window, this is what I get:

this.Request.IsAjaxRequest()
false

Why?!

回答1:

You should include jquery.unobtrusive-ajax.js if you have

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

in your web.config file, which is default enabled by MVC3 RC2. And also delete the last 3 (MicrosoftAjax, MicrosoftMvcAjax and MicrosoftMvcValidation)script references, because you don't need them when using unobtrusive version.

More info about unobtrusive Ajax by Brad Wilson