ASP.NET MVC 5 为隐藏输入呈现不同的 bool 值 [英] ASP.NET MVC 5 renders different bool value for hidden input

查看:22
本文介绍了ASP.NET MVC 5 为隐藏输入呈现不同的 bool 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下视图模型:

public class FooViewModel
{
    public bool IsBoolValue { get; set; }
}

和这个视图:

<input type="hidden" id="Whatever" data-something="@Model.IsBoolValue" value="@Model.IsBoolValue" />

隐藏输入域的输出是这样的:

The output of the hidden input field is this:

为什么value 属性没有设置为True,而data-something 属性却设置了?

How come the value attribute is not set toTrue, but the data-something attribute is?

MVC 5 中是否存在会导致此问题的更改,因为在我的 MVC 4 应用程序中不会出现此问题.

Is there a change in MVC 5 that would cause this, since in my MVC 4 apps this problem does not occur.

推荐答案

我想我已经想通了.

我相信 Razor 视图引擎遵循 HTML 5 设置布尔属性的方式,如下所述:

I believe the Razor viewengine is adhering to the HTML 5 way of setting boolean attributes, as described here:

什么当属性是布尔属性时,这是否意味着在 HTML 5 中?

在 HTML 5 中,bool 属性设置如下:

In HTML 5, a bool attribute is set like this:

因此,如果 Model.IsBoolValuetrue,Razor 视图引擎采用模型的 bool 值并将呈现(在我的情况下)value 属性.否则,如果它是 false,则 value 属性根本不会呈现.

So the Razor viewengine takes your model's bool value and will render (in my case) the value attribute if Model.IsBoolValue is true. Otherwise, if it's false then the value attribute is not rendered at all.

正如评论中提到的Zabavsky,要强制True或False的值出现在value属性中,简单使用ToString():

As mentioned Zabavsky in the comments, to force the value of True or False to appear in the value attrbiute, simple use ToString():

这篇关于ASP.NET MVC 5 为隐藏输入呈现不同的 bool 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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