2014-06-05 83 views
-1

我想了解如何向URL.Action添加額外參數,並將其作爲結果鏈接的一部分。如何通過擴展方法爲URL.Action添加額外參數

讓我們假設如下:

myParm = "myTestParameterValue"; 
@Url.Action("Edit", "Order", new { id=item.Id}, null,myParm) 

這將導致:

/Order/Edit/1/myTestParameterValue 

我會很感激的擴展方法的一些示例代碼,這個動作取樣看到參數是如何拍攝以及如何生成鏈接。

我想這將開始類似:

public static MvcHtmlString Action(this HtmlHelper helper, string actionName, string controllerName, object routeValues, boolean IsHashRequired) 

If (IsHashRequired) 
{ 
    String myHash = GetHash(); 
} 

// Pseudocode .... string myNewLink = ... + myHash 

很多感謝

編輯

我需要計算哈希值添加到結果的鏈接。更好的參數是布爾值。我已編輯相應的代碼。

EDIT2:

public static IHtmlString Action(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues, string protocol, bool isHashRequired) 
{ 

    if (isHashRequired) 
    { 
     routeValues["hash"] = "dskjdfhdksjhgkdj"; //Sample value. 
    } 
    return urlHelper.Action(???); // Resultant URL = /Order/Edit/1/dskjdfhdksjhgkdj 
} 

EDIT3:

掙扎:

return urlHelper.Action(actionName, controllerName, routeValues, protocol); 

顯然需要轉換爲IHtmlString ??

EDIT4:

public static String Action(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues, string protocol, bool isHashRequired) 
{ 

    RouteValueDictionary rvd = new RouteValueDictionary(routeValues); 
    if (isHashRequired) 
    { 
     string token = "FDSKGLJDS"; 
     rvd.Add("urltoken", token); 
    } 
    return urlHelper.Action(actionName, controllerName, rvd, protocol); //rvd is incorrect I believe 
} 

EDIT5

return urlHelper.Action(actionName, controllerName, rvd, protocol,null); 

其中

RVD是RouteValueDictionary 主機名稱爲空。

謝謝...

+0

這將成爲您路由的一部分,而不是'.Action'擴展方法的一部分。 –

+0

真的很欣賞丹尼爾在這裏的幫助,所以不知道誰downvoted和爲什麼?哦,我相信我會通過丹尼爾得到答案。 – SamJolly

回答

3

你應該考慮修改你的路由

如果你有你的路由配置添加這樣的事情:

routes.MapRoute(
    "hash",               // Route name 
    "{controller}/{action}/{id}/{hash}",        // URL with parameters 
    new { controller = "Home", action = "Index", id = "", hash = "" } // Parameter defaults 
); 

而且使用URL.Action這樣的:

myParm = "myTestParameterValue"; 
@Url.Action("Edit", "Order", new { id=item.Id, hash = myParm}, null); 

你可以很容易地添加一個新的擴展方法類

public static class MyExtensions 
{ 
    public static IHtmlString ActionWithHash(this UrlHelper urlHelper, ....) 
    { 
     if (hashRequired) 
     { 
      routeParameters["hash"] = ... 
     } 
     return urlHelper.Action(...); 
    } 
} 
+0

謝謝你。我實際上是使用這個擴展方法來添加一個安全令牌,所以需要代碼來生成一個Hash,因此需要一個擴展方法。該參數可能更可能是一個布爾值,即「IsHashRequired」,如果爲true,則計算散列並將其作爲新參數添加到生成的鏈接中。 – SamJolly

+0

問題編輯,以幫助清晰度希望..... – SamJolly

+1

@SamJolly我更新了一個簡單的例子。 –

相關問題