我有一个 Ajax 操作链接,它在 Controller 方法中请求一个字符串。我想将该字符串插入到超链接的属性中。如何指定目标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 ????????
}
最佳答案
Ajax 助手的默认行为不支持这一点。但是,您可以创建一个在 Ajax 请求返回时运行的自定义 JavaScript 处理程序,然后使用该处理程序将值注入(inject)到属性中
创建一个通用 JavaScript 文件(例如,将其加载到母版页中)并添加此函数:
// 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;
}
}
然后,在构建 Ajax 链接时:
Ajax.ActionLink("Change IMG Source", "actionChange", new AjaxOptions() {
UpdateTargetId="CHANGE-MY-SRC",
OnCompleted="createAttributeInjector('src')"
}
免责声明:我无法对此进行测试,但我已经使用 Ajax 助手完成了类似的事情。如果您有问题,请在评论中发表我的回答,我很乐意提供帮助!如果有效,请在评论中告诉我!
如果您有源代码 ( you can get it on CodePlex ),则可以查看 MicrosoftMvcAjaxScript 项目中的 AjaxContext.cs 文件,以获取可从 OnCompleted 处理程序访问的属性的完整列表
关于.net - ASP.NET MVC : AJAX ActionLink- Target an HTML attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/488726/