Search code examples
c#asp.net-mvcextension-methodsdisplayfor

c# mvc helper extension Html.DisplayFor


Hours later. Interneting later. Hair pulling later.

Prs_Role_ID_Deleted is an int .

In my Details.cshtml, I am trying to have it output a "" (empty string) if the value of model.Prs_Role_ID_Deleted = 0 (zeri).

The problem is I am unable unable to get the value of model => model.Prs_Role_ID_Deleted . I can get the property name. I can get the model.Prs_Role_ID_Deleted .

I am unable to get the value of model.Prs_Role_ID_Deleted which should equal 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";
}

I am beginning to think it is not possible to ascertain the value.


Thanks SLaks. That was the solution.

Posting solution for other developers.

AFTER SLaks advice

@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)));
}

Solution

  • You need to compile the expression to a delegate, then call it on the model:

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