布尔模型MVC中4绑定问题 [英] Boolean model binding issue in Mvc 4

查看:163
本文介绍了布尔模型MVC中4绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要绑定一个布尔属性来隐藏输入控制器,但输出HTML code是错误

I want to bind a boolean property to a hidden input controller, but the output html code was error

code如下:

public class TestModel
{
    public bool IsOk { get; set; }
    public bool IsSuccess { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new TestModel { IsOk = false, IsSuccess = true });
    }
}

<h2>Index</h2>
<p>@Model.IsOk</p>
<p>
  <input type="hidden" value="@Model.IsOk" />
</p>
<p>
  <input type="hidden" value="@Model.IsSuccess" />
</p>

HTML输出

<h2>Index</h2>
<p>False</p> //works

<p>
    <input type="hidden" /> //where is value?
</p>

<p>
    <input type="hidden" value="value" /> //wath's this?
</p>

但是,如果我使用的ToString(),以上所有工作得很好,所以这是我的错?

But if i use ToString(), all above works well, so is it my mistake?

推荐答案

在HTML,当你有哪些功能是作为一个属性的开/关或真/假开关您删除属性,当属性是关闭/假,并添加具有相同的值作为属性名属性时,属性是上/真。剃刀为您提供为你已经经历过的功能。

In HTML when you have an attribute which functions as an on/off or true/false switch you remove the attribute when the attribute is off/false and add the attribute with the same value as the attribute name when the attribute is on/true. Razor provides you with that functionality as you have already experienced.

也许你打算在视图中使用 Html.HiddenFor

Perhaps you intend to use Html.HiddenFor in the view?

<p>
    @Html.HiddenFor(m => m.IsOk)
</p>
<p>
    @Html.HiddenFor(m => m.IsSuccess)
</p>

这会产生这个HTML,你必须值=FALSE值=真为你预计:

This will produce this HTML where you have value="False" and value="True" as you expect:

<p>
    <input data-val="true" data-val-required="The IsOk field is required." 
        id="IsOk" name="IsOk" type="hidden" value="False" />
</p>
<p>
    <input data-val="true" data-val-required="The IsSuccess field is required."
        id="IsSuccess" name="IsSuccess" type="hidden" value="True" />
</p>

此外,模型绑定就能往返您查看模型属性。

Also, the model binder will be able to round-trip you view model properties.

这篇关于布尔模型MVC中4绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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