Currently my oracle table has values Y/N for Enable and Disable. When editing the row the dropdownlist shows, Enable and Disable.
<div class="form-group">
@Html.LabelFor(model => model.FLAG, htmlAttributes: new { @class ="control- label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("FLAG", new List<SelectListItem>{new SelectListItem{Text ="Enable",Value="Y",Selected=true},
new SelectListItem{Text ="Disable",Value="N"}})
@Html.ValidationMessageFor(model => model.FLAG, "", new { @class = "text-danger" })</div></div>
My Issue:
in the index page where the records are shown, the Value of the column "Y" shows. I would like to show Enabled and disabled in the index page instead of the value "Y" or the value "N". is there an html helper like the dropdownlist but a label that shows a customized text based on value as I did with the SelectListItem?
You can write a custom helper for that purpose. You can add it inside the view using the following method:
// You can use Char type instead
@helper replaceValue(String val){
if(val.ToLower().Equals("y"){
<span style="color:green"> Enabled</span>
}
else if(val.ToLower().Equals("n"){
<span style="color:red"> Disabled</span>
}
else{
<span> N/A</span>
}
}
Or you may define as an extension method for example
public static class Extensions{
public static MvcHtmlString replaceVal(this HtmlHelper html, [And your parameters]){
... // You logic here
}
}
Here is my code for custom expression:
<div class="col-md-10">
@Html.LabelCustom(model => model.FMLA_FLAG) </div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
namespace SurveyMaster.CustomHelpers
{
public static class CustomHTMLHelpers
{
public static MvcHtmlString LabelCustom<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
string displayValue = "";
string Value = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model.ToString();
if (Value == "Y")
displayValue = "Enabled";
else if(Value == "N")
displayValue = "Disabled";
return MvcHtmlString.Create(String.Format("<label for='{0}'>{1}</label>", Value, displayValue));
}
}
}