2014-02-19 25 views
1

我有一個方法GenerateLinks(),它需要一個名爲resultActionResult對象。在該方法中,我想使用result的修改版本來生成鏈接,其中包含每個id的附加id參數。請注意,HtmlHelper.ActionLink()需要ActionResult將參數添加到現有的ActionResult對象

// Client-side 
@Html.GenerateLinks(Mvc.Areas.MyArea.Index(), Model.ids); 

// Server-side 
MvcHtmlString GenerateLinks(this HtmlHelper helper, ActionResult result, List<string> ids) 
{ 
    var sb = new StringBuilder(); 
    foreach (var id in ids) 
    { 
     // How to add id to result where result becomes Mvc.Areas.MyArea.Index(id)? 
     sb.Append(helper.ActionLink(id, result-with-id-as-param); 
     sb.Append("<br/>"); 
    } 
    return new MvcHtmlString(sb.ToString()); 
} 

即使我知道有替代方法來產生這些鏈接除了使用ActionLink,我的最後一個問題是:是否有可能加入id作爲一個參數去現有ActionResult對象?如果是這樣,怎麼樣?

謝謝。

回答

0

找到了答案:

foreach (var id in ids) 
{ 
    // How to add id to result where result becomes Mvc.Areas.MyArea.Index(id)? 

    // *** ANSWER 
    result.GetRouteValueDictionary()["id"] = id; 
    // *** ANSWER 

    sb.Append(helper.ActionLink(id, result); 
    sb.Append("<br/>"); 
} 
0

修改您的ActionResult

public ActionResult Index(id = defaultvalue){ 
    //AR code here 
} 

,然後你傳遞的Id如果需要的話。您也可以設置一個defaultvalue作爲id,以防萬一傳遞。

+0

我的控制器代碼已經處理的默認狀態。我的問題是:如果可能的話,如何修改對象'result'從'Mvc.Areas.MyArea.Index()'到'Mvc.Areas.MyArea.Index(id)'? – MarkG

+0

是的,只需傳遞id即可。只要你能將這個動作結果從視圖傳遞給控制器​​,它就可以工作。 'Mvc.Areas.MyArea.Index(id)' – user3311522

+0

謝謝,我實際上找到了答案:使用'GetRouteValueDictionary.Add()'如下:'result.GetRouteValueDictionary().Add(「id」,id);'I將在8小時的時間過後發佈更清晰的答案。 – MarkG

相關問題