"routeValues"매개 변수가 다른 방식으로 전달되면 MVC 용 도우미 클래스를 만들고 문제가 있음을 발견했습니다. 이 메서드는 기본적으로 일부 특성을 정의하기 위해 만들어집니다. 아래 코드는 내 문제가 무엇인지 설명하기 위해 사용하는 스 니펫입니다.MVC 도우미, 동일한 매개 변수가있는 메서드가 다른 결과를 나타냅니다.
"routeValues"매개 변수를 허용하지 않는 "MyBeginForm()"메서드가 있고 "routeValues"매개 변수는 "BeginForm"메서드에 null로 직접 전달됩니다. 다른 메소드 "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 측
<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>
누군가 이런 일이 일어나는 이유와 내가 어떻게 해결할 수 있는지 설명해 주실 수 있습니까?
고마워요. 나는 그것이 다른 오버로딩 방법을 선택하고 있다는 것을 깨닫지 못했습니다. 다시 한번 감사드립니다. –