【发布时间】:2014-05-27 07:05:09
【问题描述】:
我正在为 MVC 创建一个辅助类,并在以不同方式传递参数“routeValues”时发现问题。默认情况下,创建这些方法是为了定义一些属性。下面的代码是我用来解释我的问题的 sn-p。
我有一个方法“MyBeginForm()”,它不接受“routeValues”的参数,“routeValues”参数直接作为空值传递给“BeginForm”方法。另一种方法“MyBeginForm(object routeValues)”接受“routeValues”的参数,我通过参数传递了“null”值。问题是生成的html不一样。
//Custom Class for custom attributes
public class MyHtmlHelper<TModel>
{
private readonly HtmlHelper<TModel> htmlHelper;
internal MyHtmlHelper(HtmlHelper<TModel> htmlHelper)
{
this.htmlHelper = htmlHelper;
}
//Here the routeValues parameter of Begin Form is passed directly to the method as null
public MvcForm MyBeginForm()
{
var myAttributes = new Dictionary<string, object>(){
{"test", "value"},
{"test2", "value2"},
};
return htmlHelper.BeginForm("Index", "Home", null, FormMethod.Post, myAttributes);
}
//Here I have passed the null value through the parameter
public MvcForm MyBeginForm(object routeValues)
{
var myAttributes = new Dictionary<string, object>(){
{"test", "value"},
{"test2", "value2"},
};
return htmlHelper.BeginForm("Index", "Home", routeValues, FormMethod.Post, myAttributes);
}
}
//This class is used for static call in html
public static class MyHtmlHelperkEx
{
public static MyHtmlHelper<TModel> MyHtmlHelper<TModel>(this HtmlHelper<TModel> htmlHelper)
{
return new MyHtmlHelper<TModel>(htmlHelper);
}
}
html端使用如下sn-p
<h1>Without Parameter</h1>
@using (Html.MyHtmlHelper().MyBeginForm()) { }
<h1>With parmeter</h1>
@using (Html.MyHtmlHelper().MyBeginForm(null)) { }
以下是生成的html。您可以看到属性的生成方式不同。
<h1>Without Parameter</h1>
<form action="/" method="post" test="value" test2="value2">
System.Web.Mvc.Html.MvcForm
</form>
<h1>With parmeter</h1>
<form comparer="System.Collections.Generic.GenericEqualityComparer`1[System.String]" count="2" keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]" action="/" method="post"></form>
有人可以解释为什么会发生这种情况以及我该如何解决。
【问题讨论】:
标签: c# html asp.net-mvc-4 generics form-helpers