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 field of the target id element?
<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 ????????
}
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
I'm not sure exactly what you mean but you can provide a set of HTML attributes some versions of the ActionLink extension.
Ajax.ActionLink( string linkText,
string action,
object routeValues,
AjaxOptions ajaxOptions,
object htmlAttributes )
Example:
<%= 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." } ); %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With