JenniferWalters JenniferWalters - 1 year ago 144
C# Question

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")

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 = "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 = "";
OutputValue = ctlValue.ToString();
return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}", wrapperTag, id, OutputValue, helper.DisplayFor(expression)));

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download