Begin.Form,带有重载,接受routeValues和htmlAttributes

时间:2009-06-24 13:36:12

标签: asp.net-mvc

我使用了接受routeValues

的Begin.Form重载
    <% 
        RouteValueDictionary routeValues = ViewContext.RouteData.Values;
        routeValues.Add("TestRoute1", "test");

        using (Html.BeginForm(
            "Category", 
            "Home",
              routeValues,
              FormMethod.Post

      ))
       { %>  

        <input type="submit" value="submit" name="subform" />
<% }%>

这很好用,并将formtag呈现为:

<form method="post" action="/Home/Category?TestRoute1=test">

我需要更改htmlAttributes,这就是我使用的原因:

    <% 
        RouteValueDictionary routeValues = ViewContext.RouteData.Values;
        routeValues.Add("TestRoute1", "test");

        using (Html.BeginForm(
            "Category", 
            "Home",
              routeValues,
              FormMethod.Post,
              new {id="frmCategory"}

      ))
       { %>  

        <input type="submit" value="submit" name="subform" />
<% }%>

结果完全错误:

<form method="post" id="frmTyreBySizeCar" action="/de/TyreSize.mvc/List?Count=12&amp;Keys=System.Collections.Generic.Dictionary%....

我可以在Formhelper的来源中看到原因是什么。

有2个重载适用于我给定的参数:

public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes)

public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes)

出错了,因为拾取了第一种方法。如果我不提供htmlAttributes,那么对象作为参数没有重载,并且everyrthing按预期工作。

我需要一个接受RouteValues和htmlAttributes字典的解决方法。我看到有重载有一个额外的routeName,但那不是我想要的。

编辑:eugene显示了BeginForm的正确用法。

Html.BeginForm("Category", "Home",
new RouteValueDictionary { {"TestRoute1", "test"} },
FormMethod.Post,
new Dictionary<string, object> { {"id", "frmCategory"} }

3 个答案:

答案 0 :(得分:32)

使用(RouteValues和HtmlAttributes都是对象):

Html.BeginForm("Category", "Home",
    new { TestRoute1 = "test" },
    FormMethod.Post,
    new { id = "frmCategory" }
)

或(RouteValues和HtmlAttributes都是字典):

Html.BeginForm("Category", "Home",
    new RouteValueDictionary { {"TestRoute1", "test"} },
    FormMethod.Post,
    new Dictionary<string, object> { {"id", "frmCategory"} }
)

答案 1 :(得分:2)

using (Html.BeginForm("Category", "Home", new { TestRoute1="test"}, 
       FormMethod.Post, new {id="frmCategory"})) {

渲染

<form action="/accountchecker/Home/Category?TestRoute1=test" 
    id="frmCategory" method="post">
    <input type="submit" value="submit" name="subform" />
</form>

答案 2 :(得分:2)

你可以写

<% using (Html.BeginForm("Category", "Home", new {TestRoute1=HttpContext.Current.Request.QueryString["TestRoute1"] }, FormMethod.Post, new {id = "MainForm" })) { %>
相关问题