【问题标题】:ASP.NET MVC : AJAX ActionLink- Target an HTML attributeASP.NET MVC:AJAX ActionLink - 以 HTML 属性为目标
【发布时间】:2010-10-04 01:48:30
【问题描述】:

我有一个 Ajax actionlink,它在控制器方法中请求一个字符串。我想将该字符串插入到超链接的属性中。如何指定目标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 ????????
}

【问题讨论】:

    标签: .net asp.net-mvc asp.net-ajax


    【解决方案1】:

    我不确定您的确切意思,但您可以在某些版本的 ActionLink 扩展中提供一组 HTML 属性。

    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." } ); %>
    

    【讨论】:

    • Target ID是一个图片标签,当ajax调用返回“new text”时,我想把标签的src属性改成src="new text"。
    【解决方案2】:

    我猜要简单得多,您可以使用 Url.Action(您设置的操作返回您想要的字符串,但不是返回,而是使用 Response.Write(...)。

    或者更简单,您可以在标签中使用 src=""!

    我看到您已经有了解决方案,但这可以节省您下次的时间..

    【讨论】:

      【解决方案3】:

      Ajax 助手的默认行为不支持这一点。但是,您可以创建一个在 Ajax 请求返回时运行的自定义 JavaScript 处理程序,然后使用它将值注入到属性中

      创建一个通用的 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 助手做过类似的事情。如果您有问题,请在 cmets 中发布我的答案,我很乐意提供帮助!如果可行,请在 cmets 中告诉我!

      如果您有源代码 (you can get it on CodePlex),您可以查看 MicrosoftMvcAjaxScript 项目中的 AjaxContext.cs 文件以获取可以从 OnCompleted 处理程序访问的属性的完整列表

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        • 2014-04-09
        相关资源
        最近更新 更多