更改Html.DisplayFor布尔值复选框MVC [英] Changing Html.DisplayFor boolean checkbox MVC

查看:128
本文介绍了更改Html.DisplayFor布尔值复选框MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布尔属性IsActive.视图中是具有其属性(包括IsActive)的对象的列表.但是在列表中,IsActive是一个不可编辑的复选框,因为它是布尔值.如果我将DisplayFor()更改为DisplayTextFor(),则它将仅显示True或false而不是复选框.如何在True为True而Inactive为false的情况下将True和false更改为'Active'和'Inactive'?

I have a boolean property IsActive. In the view is a list of objects with their properties (including IsActive). But in the list the IsActive is a non-editable checkbox since it's boolean. If I change DisplayFor() to DisplayTextFor() then it will just display True or false instead of checkbox. How can I change True and false to 'Active' and 'Inactive' where Active is true and Inactive is false?

      @Html.DisplayTextFor(modelItem => item.IsActive) 

然后将有效"设置为绿色,将无效"设置为红色

And then I would style the 'Active' to green and 'Inactive' to red

推荐答案

您可以使用显示模板来格式化属性的显示方式.

You can use a display template to format the way your property is displayed.

~/Shared下或将使用此模板的视图所在的View文件夹中创建一个DisplayTemplates文件夹.

Create a DisplayTemplates folder either under ~/Shared or in the View folder where the view that will be using this template exists.

向此文件夹添加新的局部视图.随便命名,例如IsActive.cshtml

Add a new partial view to this folder. Name it anything you'd like, e.g. IsActive.cshtml

@model bool
@if (Model == true)
{
    @Html.Encode("Active")
}
@if (Model == false)
{
    @Html.Encode("Inactive")
}

现在向您的媒体资源添加数据注释,以使其知道使用此显示模板.

Now add data annotation to your property to let it know to use this display template.

[UIHint("IsActive")]
public bool IsActive { get; set; }

在具有此注释的任何布尔上使用Html.DisplayFor,它将根据具有匹配名称的显示模板进行格式化.通过一些调整,您可以将颜色更改样式直接放置在显示模板中.

Use Html.DisplayFor on any bool with this annotation and it will be formatted according to the display template with the matching name. With some tweaking, you can place the color change style directly in your display template.

这篇关于更改Html.DisplayFor布尔值复选框MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆