簡體   English   中英

ASP.NET MVC:AJAX ActionLink-定位HTML屬性

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

我有一個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 ????????
}

Ajax幫助程序的默認行為不支持此操作。 但是,您可以創建在Ajax請求返回時運行的自定義JavaScript處理程序,然后使用該處理程序將值注入屬性

創建一個通用的JavaScript文件(例如,在Master頁面中加載它)並添加此功能:

// 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助手做了類似的事情。 如果您遇到問題,請在評論中發帖,我很樂意為您提供幫助! 如果有效,請在評論中告訴我!

如果您有源代碼( 可以在CodePlex上獲取 ),可以查看MicrosoftMvcAjaxScript項目中的AjaxContext.cs文件,以獲取可以從OnCompleted處理程序訪問的屬性的完整列表。

我不確定你的意思,但你可以提供一些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." } ); %>

更簡單的我猜,你可以使用Url.Action(你設置一個返回你想要的字符串的動作,但不是返回你使用Response.Write(...)。

或者甚至更簡單,你在標簽中使用src =“<%= ViewData [”src“]%>”!

我看到你已經有了解決方案,但這可以節省你下次的時間..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM