【问题标题】:How do I display a different label text from the value as done with a dropdown list in MVC 5 EF 6?如何在 MVC 5 EF 6 中使用下拉列表显示与值不同的标签文本?
【发布时间】:2016-01-04 20:59:13
【问题描述】:

目前我的 oracle 表的启用和禁用值是 Y/N。编辑下拉列表显示的行时,启用和禁用。

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

我的问题:

在显示记录的索引页面中,“Y”列的值显示。我想在索引页面中显示启用和禁用,而不是值“Y”或值“N”。是否有像下拉列表这样的 html 帮助程序,但有一个标签显示基于值的自定义文本,就像我对 SelectListItem 所做的那样?

【问题讨论】:

    标签: asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6


    【解决方案1】:

    这是我的自定义表达式代码:

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

    【讨论】:

    • 您也可以使用TagBuilder类型以更高效的方式生成HTML。
    • 我试过了,但我无法让它为标签工作。我可以将它用于文本框,因为我能够设置属性值,但我不确定如何处理标签。
    【解决方案2】:

    您可以为此编写自定义帮助程序。您可以使用以下方法将其添加到视图中:

    // 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>
        }
    }
    

    或者您可以定义为扩展方法,例如

    public static class Extensions{
        public static MvcHtmlString replaceVal(this HtmlHelper html, [And your parameters]){
            ... // You logic here
         }
    }
    

    【讨论】:

    • 谢谢,我发布了自定义助手类的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多