首页 文章

c#mvc helper extension Html.DisplayFor

提问于
浏览
0

几个小时以后。以后互相干扰。头发拉后。

Prs_Role_ID_Deleted 是一个 int。

在我的 Details.cshtml 中,如果 model.Prs_Role_ID_Deleted = 0(zeri)的值,我试图让它输出一个“”(空字符串)。

问题是我无法获得 model => model.Prs_Role_ID_Deleted 的值。我可以得到属性名称。我可以得到 model.Prs_Role_ID_Deleted。

我无法得到 model.Prs_Role_ID_Deleted 的值,它应该等于 22。

@Html.ZZZ(model => model.Prs_Role_ID_Deleted)

public static MvcHtmlString ZZZ<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
    var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
    return "whatever";
}

我开始认为不可能确定价值。


谢谢 SLaks。那就是解决方案。

为其他开发人员发布解决方案。

之后 SLAK 建议@Html.DisplayForWithID_ZeroIsBlank(model => model.Prs_Role_ID_Deleted,“span”)

- 

public static MvcHtmlString DisplayForWithID_ZeroIsBlank(this HtmlHelper helper,Expression> expression,string wrapperTag =“span”){var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)); TModel model =(TModel)helper.ViewContext.ViewData.ModelMetadata.Model; var ctlValue = expression.Compile()(helper.ViewData.Model); string OutputValue =“傻开发者。这只适用于 int。”;类型 type = ctlValue.GetType(); if(type.Equals(typeof(int))) {string s = ctlValue.ToString().Trim(); if(ctlValue == null || ctlValue.ToString().Trim() ==“0”){} else {{。4}}返回 MvcHtmlString.Create(string.Format(“<{0} id="{1}"> {2}”,wrapperTag, id,OutputValue,helper.DisplayFor(expression)));}

1 回答

  • 3

    您需要将表达式编译为委托,然后在模型上调用它:

    expression.Compile()(helper.ViewData.Model);
    

相关问题