2011-02-09 4 views
2

後、私は次のように言語を変更するためのボタンをレンダリング行いますどのようにすべてのルート値を取得する{コントローラ}/{方法}

    <%: Html.ActionLink(
         "EN", 
         ViewContext.RouteData.Values["action"].ToString(), 
         new { lang = "en" }, new { @class="tab" })%> 

次のようにこれは私のリンクをレンダリングします:{...}\en\MyController\MyMethod - 残りの問題は、メソッドの名前の後に続くすべてのルーティング値を失うことだけです。それらをどのように追加することも可能ですか?

ありがとうございました!

答えて

2

私は実際にいくつかの便利な拡張メソッドを使用します。

public static RouteValueDictionary ToRouteValueDictionary(this NameValueCollection collection) 
    { 
     RouteValueDictionary dic = new RouteValueDictionary(); 
     foreach (string key in collection.Keys) 
      dic.Add(key, collection[key]); 

     return dic; 
    } 

    public static RouteValueDictionary AddOrUpdate(this RouteValueDictionary dictionary, string key, object value) 
    { 
     dictionary[key] = value; 
     return dictionary; 
    } 

    public static RouteValueDictionary RemoveKeys(this RouteValueDictionary dictionary, params string[] keys) 
    { 
     foreach (string key in keys) 
      dictionary.Remove(key); 

     return dictionary; 
    } 

は、これは私には、次のことを行うことができます

//Update the current routevalues and pass it as the values. 
@Html.ActionLink("EN", ViewContext.RouteData.Values["action"], ViewContext.RouteData.Values.AddOrUpdate("lang", "en")) 

//Grab the querystring, update a value, and set it as routevalues. 
@Html.ActionLink("EN", ViewContext.RouteData.Values["action"], Request.QueryString.ToRouteValueDictionary.AddOrUpdate("lang", "en")) 
+0

ありがとうございました - 拡張子を持つ素敵なアイデアを。私はまだ拡張機能の概念に慣れていませんが、それは本当にそのような要求に対しては良いことです。 – sl3dg3

+0

拡張メソッドは非常に強力で、MVCとLinqの動作の中核部分です。ここで私はjQueryのアイデアをコピーして、連鎖を可能にしました。 – Gidon

0

私はあなたが仕事をするための新しいHTMLヘルパーを作成することを示唆しています、あなたが望むものをビューの中でやっていくうえで、きちんとしたやり方がないからです。それは次のようになります:

public static class MyHtmlHelpers { 
    public static MvcHtmlString ChangeLanguageLink(this HtmlHelper html, string label, string newLang) { 
    html.ViewContext.RouteData.Values["lang"] = newLang; 
    return html.ActionLink(label, html.ViewContext.RouteData.Values["action"], ViewContext.RouteData.Values); 
    } 
} 

をそして、これは、ビューでそれを使用する方法である:

<%: Html.ChangeLanguageLink("EN", "en") %> 
+0

良い入力 - 私は似たようなものを考えましたが、それがなければ可能でなければならないという印象を受けました。どうも。 – sl3dg3

関連する問題