我创建了自己的 Html Helper,它在任何必填字段中添加了红色星号。
它成功地与两者一起使用
@Html.myLabelFor(model => model.Description)
//and
@Html.myLabelFor(model => model.Description, new { /*stuff*/ })
但是,一些代码行如下
@Html.myLabelFor(model => model.Description, "Deletion Reason", new { /*stuff*/ })
我的方法不是为处理 3 个参数而设计的,所以我添加了一个可以处理 3 个参数的调用者
public static MvcHtmlString myLabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, string labelText, Object htmlAttributes)
{
return myLabelFor(html, expression, labelText, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
以下是其他正常工作的方法(包括内部方法,它包含所有必要的代码以及我用作参考的结构)
public static MvcHtmlString myLabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, IDictionary<String, Object> htmlAttributes)
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression), null, htmlAttributes);
}
public static MvcHtmlString myLabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression)
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression), null);
}
public static MvcHtmlString myLabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, Object htmlAttributes)
{
return myLabelFor(html, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
//USED ITS STRUCTURE AS A REFERENCE
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName,
String labelText = null, IDictionary<String, Object> htmlAttributes = null)
从逻辑上讲,我期望参数 labelText 会从上面的代码行中获取“删除原因”的值。但是,它在我的 3 参数方法中引发了 StackOverflowException。微软的描述含糊不清,额外的解释没有帮助,额外的解决方案正在使用
Expression<Func<TModel, string>> expression instead of my Expression<Func<TModel, TValue>> expression
我不明白我做错了什么。在这一点上,我只能想到“摆弄参数直到它起作用”,但我希望有更优雅的解决方案来解决这个问题。
PS:请让我知道我的内部助手代码是否有助于解决问题。