Ajax.ActionLink not working, Response.IsAjaxRequest() is always false

前端 未结 3 799
刺人心
刺人心 2020-12-13 06:58

I have been googling/SO:ing this issue for a while and many seem to be sharing this, but I haven\'t found any successful solution to my problem.

Using MVC3 and Razor

相关标签:
3条回答
  • 2020-12-13 07:41

    By default ASP.NET MVC 3 uses unobtrusive jquery with all the Ajax.* helpers. So start by getting rid off all MicrosoftAjax scripts (this useless c**p) and put the following instead:

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

    and then simply activate unobtrusive AJAX in your web.config (if not already done):

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

    Now jquery is going to unobtrusively AJAXify all the links containing those HTML 5 data-* attributes.

    Or even better IMHO:

    In your view simply:

    @Html.ActionLink("Update", "AjaxTester", new { id = "mylink" })
    

    and in a separate javascript file AJAXify this anchor:

    $(function() {
        $('#mylink').click(function() {
            $('#AjaxTestDiv').load(this.href);
            return false;
        });
    });
    
    0 讨论(0)
  • 2020-12-13 07:48

    For those still facing this issue:

    You should have below files in your project somewhere:

    If not, below is the nuget package, either download this from nuget manager in your visual studio project or package manager console: https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Validation/3.2.11/

    Give reference of above added file after the jquery.min.js latest version in either your respective view or layout file:

    0 讨论(0)
  • 2020-12-13 07:57

    Another IE-specific issue that can keep ActionLink from functioning correctly is covered here: ASP.NET MVC - Prevent Cache on Ajax.ActionLinks

    Basically, IE sometimes caches Ajax GET requests, so setting the AjaxOption's HttpMethod to POST is a less fragile way to construct an ActionLink:

    @Ajax.ActionLink(
           item.Name + " (Ajax link test)",
             "MyActionName",
             routeValues: new { id = item.Id },
             ajaxOptions: new AjaxOptions()
             {
                  UpdateTargetId = "divToUpdate",
                  InsertionMode = InsertionMode.Replace,
                  HttpMethod = "POST"
             })
    
    0 讨论(0)
提交回复
热议问题