【问题标题】:c# mvc helper extension Html.DisplayForc# mvc helper extension Html.DisplayFor
【发布时间】:2017-03-14 20:22:55
【问题描述】:

几小时后。以后上网。稍后拉头发。

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。这就是解决方案。

为其他开发者发布解决方案。

在 SLaks 建议之后

@Html.DisplayForWithID_ZeroIsBlank(model => model.Prs_Role_ID_Deleted, "span")
<dd><span id="Prs_Role_ID_Deleted"></span></dd>

public static MvcHtmlString DisplayForWithID_ZeroIsBlank<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> 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 = "Silly developer. This only works for int.";
    Type type = ctlValue.GetType();
    if (type.Equals(typeof(int)))
    {
        string s = ctlValue.ToString().Trim();
        if (ctlValue == null || ctlValue.ToString().Trim() == "0")
        {
            OutputValue = "";
        }
        else
        {
            OutputValue = ctlValue.ToString();
        }
    }
    return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}</{0}>", wrapperTag, id, OutputValue, helper.DisplayFor(expression)));
}

【问题讨论】:

  • 为什么不创建一个视图模型并在那里进行所有转换?
  • Fran,我认为 MVC 的工作方式是“模型”只包含纯数据的模型。输出格式可以在 cshtml、JS 或 helper 扩展中。对我来说,组合输出格式就像把汉堡和冰淇淋放在同一个盘子里。是的,它可以做到,但它会变得非常草率。
  • 视图模型与格式化输出无关,视图模型包含页面的数据项。究竟什么是纯数据?

标签: c# asp.net-mvc extension-methods displayfor


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多