Helper function for boolean property to display "yes" or "no"
I am trying to create my own helper function in ASP.NET MVC 3. Not sure if I am on the correct path. I have a boolean prop开发者_StackOverflow社区erty called Active, when I display the property on the display view then the text is either "True" or "False". So I thought of writing my own helper that accepts this boolean value and either returns "Yes" or "No". Do I need a helper for this, or is there a shorter way?
This is what I currently have, it does not compile, can someone please help me here? The accompanying unit test will be appreciated.
public static IHtmlString ConvertBooleanToYesNo(this HtmlHelper htmlHelper, bool value)
{
string str = string.Empty;
if (value)
{
return htmlHelper.Encode("Yes");
}
else
{
return htmlHelper.Encode("No");
}
}
UPDATE
Error is:
Cannot implicitly convert type 'string' to 'System.Web.IHtmlString'
I know I have to convert it, but was just wondering if this was the best way to do it?
HtmlHelper.Encode returns a String object not an IHtmlString.
Use return new HtmlString("Yes");
Or simply
public static IHtmlString ConvertBooleanToYesNo(this HtmlHelper htmlHelper, bool value) {
return new HtmlString(value ? "Yes" : "No");
}
The HtmlString class will handle encoding for you but in the case of a simple 'Yes/No' string, no encoding is required.
精彩评论