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

Mat*_*s F 19 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" />
<% }%>
Run Code Online (Sandbox Code Playgroud)

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

<form method="post" action="/Home/Category?TestRoute1=test">
Run Code Online (Sandbox Code Playgroud)

我需要更改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" />
<% }%>
Run Code Online (Sandbox Code Playgroud)

结果完全错了:

<form method="post" id="frmTyreBySizeCar" action="/de/TyreSize.mvc/List?Count=12&amp;Keys=System.Collections.Generic.Dictionary%....
Run Code Online (Sandbox Code Playgroud)

我可以在Formhelper的源代码中看到原因是什么.

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

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)
Run Code Online (Sandbox Code Playgroud)

它出错了,因为第一种方法被拿起来了.如果我不提供htmlAttributes,那么没有对象作为参数的重载,并且everyrthing按预期工作.

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

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

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

)

eu-*_*-ne 32

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

Html.BeginForm("Category", "Home",
    new { TestRoute1 = "test" },
    FormMethod.Post,
    new { id = "frmCategory" }
)
Run Code Online (Sandbox Code Playgroud)

或(RouteValues和HtmlAttributes都是字典):

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