我已经创建了自己的 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。 Microsoft description含糊不清,additional explanation没有帮助,additional solution正在使用
Expression<Func<TModel, string>> expression instead of my Expression<Func<TModel, TValue>> expression
我不明白我做错了什么。在这一点上,我只能想到“摆弄参数直到它起作用”,但我希望有更优雅的解决方案来解决这个问题。
PS:请让我知道我的内部助手代码是否有助于解决问题。
最佳答案
您在第一次重载时遇到异常,因为该方法正在递归调用自身,并一直这样做直到执行堆栈溢出。你需要改变而不是自称
return myLabelFor(html,
expression,
labelText,
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
到
return LabelHelper(html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
labelText,
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
根据您的评论,使用 return myLabelFor(...)
的第 4 个重载没有抛出异常的原因是它调用了您的第 2 个重载,后者又调用了 return LabelHelper( ...)
我建议您将第 4 个重载更改为直接调用 LabelHelper()
,并将所有公共(public)重载更改为显式调用 LabelHelper()
,传递所有 4 个参数,这是内置的`HtmlHelper 扩展方法使用的模式(您可以查看 source code for LabelFor() here )
关于c# - MVcHtmlString 中的堆栈溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38003156/