ASP.NET MVC : AJAX ActionLink- Target an HTML attribute

后端 未结 3 532
名媛妹妹
名媛妹妹 2021-01-13 01:35

I have an Ajax actionlink that requests a string in the controller method. I want to insert that string into an attribute of a hyperlink. HOw do I specify the attribute fiel

3条回答
  •  梦毁少年i
    2021-01-13 02:04

    The default behavior for the Ajax helpers won't support this. You can, however, create a custom JavaScript handler that is run when the Ajax request returns, and then use that to inject the value into the attribute

    Create a common JavaScript file (load it up in the Master page, for example) and add this function:

    // Creates an Ajax OnComplete handler that will inject 
    ///the contents into the specified attribute, rather than the InnerHtml
    function createAttributeInjector(attributeName) {
        return function(ajaxContext) {
            if(ajaxContext.get_updateTarget() !== null) {
                ajaxContext.get_updateTarget()[attributeName] = ajaxContext.get_data();
            }
            // IMPORTANT: Suppress the default behavior!
            return false;
        }
    }
    

    Then, when building your Ajax link:

    Ajax.ActionLink("Change IMG Source", "actionChange", new AjaxOptions() {
        UpdateTargetId="CHANGE-MY-SRC", 
        OnCompleted="createAttributeInjector('src')"
    }
    

    Disclaimer: I haven't been able to give this a test, but I've done similar things with the Ajax helpers. Post in the comments for my answer if you have problems and I'm happy to help! If it works, let me know in the comments as well!

    If you have the source (you can get it on CodePlex), you can check out the AjaxContext.cs file in the MicrosoftMvcAjaxScript project for a full list of the properties you can access from the OnCompleted handler

提交回复
热议问题