ASP.NET MVC: AJAX ActionLink - Customize HTML Attribute

I have an Action Ajax link that requests a string in a controller method. I want to insert this line into a hyperlink attribute. HOw Do I indicate the attribute field of the target ID?

<img id="CHANGE-MY-SRC" src=ViewData["src"] >

<%=Ajax.ActionLink("Change IMG Source","actionChange",new AjaxOptions()         
UpdateTargetId="CHANGE-MY-SRC"})%>

public string actionChange()
{
   ViewData["src"]= "somethingNew";

   return ????????
}
+5
source share
3 answers

The default behavior for Ajax helpers will not support this. However, you can create your own JavaScript handler that runs when the Ajax request returns, and then use it to insert the value into the attribute

Create a shared JavaScript file (for example, upload it on the main page) 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, creating an Ajax link:

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

: , Ajax. , , ! , !

( CodePlex), AjaxContext.cs MicrosoftMvcAjaxScript , OnCompleted

+8

, , HTML ActionLink.

Ajax.ActionLink( string linkText,
                 string action,
                 object routeValues,
                 AjaxOptions ajaxOptions,
                 object htmlAttributes )

:

<%= Ajax.ActionLink( "add",
                     "AddThing",
                     new { id = ViewData.Model.ID },
                     new AjaxOptions { Confirm = "Are you sure?",
                                       UpdateTargetId = "thingList"
                                     },
                     new { title = "Add a thing to the database." } ); %>
+2

Much easier, you could use Url.Action (the action you set to return the desired line, but instead of returning you use Response.Write (...).

Or even simpler, you use src = "<% = ViewData [" src "]%>" in your tag!

I see that you already have a solution, but it can save your time next time.

0
source

All Articles