[英]Showing Yes/No instead of checkbox in the View of ASP.Net MVC
I am very new to ASP.Net / MVC . 我是ASP.Net / MVC的新手。 I have created a View that I am populating from a model. 我创建了一个我从模型中填充的视图。 I am creating a rows for each item in the model to show their properties/attributes of model item. 我正在为模型中的每个项创建一个行,以显示模型项的属性/属性。
One of the member is a bool , name is Staged. 其中一个成员是bool,名字是Staged。 In the View I want to display it as Yes if true or No if false. 在视图中我想将其显示为是(如果为true)或否则显示为否。 The user will only be able to read it, so simple text Yes/No shall be sufficient. 用户只能阅读它,所以简单的文字是/否就足够了。
I am using the following code in the cshtml 我在cshtml中使用以下代码
<td>
@Html.DisplayFor(modelItem => item.Staged)
</td>
This however shows a checkbox in the place, how can I show it as Yes/No ? 但是,这会在该位置显示一个复选框,如何将其显示为是/否?
Thanks, 谢谢,
You could use a custom html helper extension method like this: 你可以使用这样的自定义html助手扩展方法:
@Html.YesNo(item.Staged)
Here is the code for this: 这是以下代码:
public static MvcHtmlString YesNo(this HtmlHelper htmlHelper, bool yesNo)
{
var text = yesNo ? "Yes" : "No";
return new MvcHtmlString(text);
}
This way you could re-use it throughout the site with a single line of Razor code. 通过这种方式,您可以使用一行Razor代码在整个站点中重复使用它。
use Html.Raw and render the string conditionally based on model value true/false 使用Html.Raw并根据模型值true / false有条件地呈现字符串
<td>
@Html.Raw((Model.Staged)?"Yes":"No")
</td>
In the model, you would need to make a new property that does something like this... 在模型中,您需要创建一个类似于此的新属性...
public string ItemStagedYesNo = (item.Staged) ? "Yes" : "No";
then in the view, do 然后在视图中,做
@Html.DisplayFor(modelItem => ItemStagedYesNo);
Change 更改
@Html.DisplayFor(modelItem => item.Staged)
to 至
@(item.Staged?"Yes":"No")
This is the simplest way to achieve what your requirements. 这是实现您的要求的最简单方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.