2012-12-30 30 views

回答

4

明確定義嘗試參數htmlAttributes像這樣:

@using (Html.BeginForm(null, null, FormMethod.Post, htmlAttributes: new { @class = "form-class" })) { 
} 

更新後閱讀評論 嘗試使用一個BeginForm重載,允許您指定路由目標ects(我沒有測試過,因爲我附近沒有IDE)

@using (Html.BeginForm("Action", "Controller", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, htmlAttributes: new { @class = "form-class" })) { 
} 
+0

非常感謝。我將如何包含ReturnUrl = ViewBag.ReturnUrl? –

+0

不客氣。查看更新。 – Ben

2

如果你想使用默認的表單,但只是添加一些屬性,這是一個痛苦。 Here is the overloaded method signature that accepts attributes。因此,您還需要提供操作名稱,控制器名稱和表單方法。第一種形式是設置RouteValueCollection。

我過去所做的是創造我自己的幫手,規避限制。下面是一個示例擴展方法來短路所有其他參數。

using System.Web.Mvc.Html; 

namespace MySite.Extensions { 
    public static class HtmlFormExtensions { 
     public static MvcForm BeginForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues, IDictionary<string, Object> htmlAttributes) { 
      return htmlHelper.BeginForm(null, null, routeValues, FormMethod.Post, htmlAttributes); 
     } 
    } 
} 

一定要在視圖中包括命名空間(或者通過web.config中的所有視圖),然後調用它像這樣:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }, new { @class = "form" })) 
相關問題