2013-01-24 48 views
1

我有一個複雜的路由,我想用HtmlHelper.BeginForm方法匹配。我已經閱讀了很多關於使用路由值字典和對象初始值設定項和html屬性的文章和答案。但他們都達不到我想要做的......使用HtmlHelper.BeginForm匹配複雜的路由

這裏是路線我想匹配:

// Attempt to consolidate all Profile controller actions into one route 
routes.MapRoute(
    "Profile", 
    "{adminUserCode}/{controller}s/{customerId}/{action}/{profileId}", 
    new { adminUserCode = UrlParameter.Optional, controller = "Profile"}, 
    new { adminUserCode = @"\d+", customerId = @"\d+", profileId = @"\d+" } 
); 

的控制器&動作的一個例子網址我想用這場比賽將是:

http://mysite.com/123/Profiles/456/UpdatePhoneNumber/789

隨着在POST身體

而且這裏的實際電話號碼是位於C1 osest語法我來得到正確的:

@using (Html.BeginForm(
    "UpdatePhoneNumber", 
    "Profile", 
    new { 
     customerId = Model.LeadProfile.CustomerId, 
     profileId = Model.CustomerLeadProfileId 
    })) 
{ 
    <!-- the form --> 
} 

但是,這把參數的對象作爲查詢字符串參數,就像這樣:

<form method="post" 
    action="/mvc/123/Profiles/UpdatePhoneNumber?customerId=78293&profileId=1604750"> 

我只是想一時興起這種語法,但它的輸出同樣的事情,其他的過載

@using (Html.BeginForm(new 
{ 
    controller = "Profile", 
    customerId = Model.LeadProfile.CustomerId, 
    action = "UpdatePhoneNumber", 
    profileId = Model.CustomerLeadProfileId 
})) 

我知道我可以退回到原始的HTML這裏,但看起來應該有辦法讓愚蠢的HtmlHelper匹配比最淺更多路線。

回答

1

如果你想使用你的表格複雜的路線,你需要使用BeginRouteForm Method

@using (Html.BeginRouteForm("Profile", new 
{ 
    controller = "Profile", 
    customerId = Model.LeadProfile.CustomerId, 
    action = "UpdatePhoneNumber", 
    profileId = Model.CustomerLeadProfileId 
})) 
+0

這確實的伎倆。我有些驚訝,我所看到的資源都沒有提到'BeginRouteForm'方法。簡單地閱讀MSDN,我沒有任何可以找到的例子或散文來解釋差異,所以也許並不奇怪。我注意到,如果我只是做'Html.BeginRouteForm(「Profile」)',它用當前值填充整個路由,但是如果我嘗試傳遞'new {action =「UpdatePhoneNumber」}',它會失敗。不過,您可以刪除新對象中冗餘的'controller'屬性。謝謝! –