2011-07-14 18 views
10

當URL被使用Url.Action幫手,如果頁面包含類似於ASP.Net MVC 3 Url.Action方法使用的參數值從先前的請求

@ Url.Action(「編輯」的線自動生成, 「學生」)

預計會產生像domain/student/edit這樣的網址,並按預期工作。 但是,如果請求的url包含一些參數,如domain/student/edit/210,上面的代碼使用以前請求中的這些參數,並生成類似的東西,即使我沒有爲Action方法提供任何此類參數。

簡而言之,如果請求的url包含任何參數,頁面(爲該請求提供服務)的任何自動生成的鏈接也將包含這些參數,無論我在Url.Action方法中是否指定它們。

什麼錯?

回答

8

怪異,似乎無法重現該問題:

public class HomeController : Controller 
{ 
    public ActionResult Index(string id) 
    { 
     return View(); 
    } 

    public ActionResult About(string id) 
    { 
     return View(); 
    } 
} 

和內部Index.cshtml

@Url.Action("About", "Home") 

現在,當我要求/home/index/123網址助手產生/home/about預期。沒有幻影參數。那麼你的情況如何不同?


UPDATE:

現在你已經澄清你的情況看來你具備以下條件:

public class HomeController : Controller 
{ 
    public ActionResult Index(string id) 
    { 
     return View(); 
    } 
} 

和內部Index.cshtml你要使用:

@Url.Action("Index", "Home") 

如果您要求/home/index/123這會生成/home/index/123而不是預期的/home/index(或簡單/考慮到默認值)。

此行爲是設計使然。如果你想改變它,你將不得不編寫自己的幫手,忽略當前的路線數據。以下是它的外觀:

@UrlHelper.GenerateUrl(
    "Default", 
    "index", 
    "home", 
    null, 
    Url.RouteCollection, 
    // That's the important part and it is where we kill the current RouteData 
    new RequestContext(Html.ViewContext.HttpContext, new RouteData()), 
    false 
) 

這會生成您期望的正確url。當然這很醜陋。我建議你將它封裝到一個可重用的幫助器中。使用的參數和供應空

+0

不是這樣,嘗試爲沒有參數的同一頁面生成鏈接,但是請求帶有參數的頁面。所以在你的情況下,嘗試爲索引頁面本身生成鏈接。 –

+0

@Threecoins,啊,好吧,明白了。這是設計。 –

+0

哦,所以如果請求有參數,我不能在同一頁面內生成一個沒有參數的鏈接? –

0

使用ActionLink的過載。

@Url.Action("Edit","Student", new { ID = "" }) 
+0

好像我不能將null分配給匿名屬性類型。 –

+1

這也行不通。 –

+0

@Mathew將'null'強制轉換爲'dynamic'將其分配給匿名屬性類型。但是,像達林說的,是的,這是行不通的。 – MasterMastic

0

你可以爲這個動作,例如註冊自定義路線:

routes.MapRoute("Domain_EditStudentDefault", 
      "student/edit", 
      new { 
       controller = MVC.Student.Name, 
       action = MVC.Student.ActionNames.Edit, 
       ID = UrlParameter.Optional 
      }, 
      new object(), 
      new[] { "MySolution.Web.Controllers" } 
     ); 

然後你可以使用url.RouteUrl("Domain_EditStudentDefault")網址RouteUrl幫手覆蓋,只有routeName其中不帶參數生成的URL參數。

相關問題