本文介绍了MVC 4自定义模板的布尔(剃刀)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Twitter的引导框架,因此得到EditorFor和DisplayFor方法来输出我需要什么,我创建自定义模板,每个为我登录页面我想了rememberMe像字符串,文本,密码等类型的布尔,所以和以前一样,我创建了下面的模板,并把在Boolean.cshtml:

I am using the twitter bootstrap framework, so to get the EditorFor and DisplayFor methods to output what I need, I created custom templates for each of the types like string, text, password etc. For my login page I want a RememberMe bool, so as before, I created the following template and put in in Boolean.cshtml:

@model bool

<div class="control-group">
    <div class="controls">
        <label class="checkbox">
            @Html.CheckBoxFor(m => m, new {@class = "checkbox"})
            @Html.LabelFor(m => m)
        </label>
    </div>
</div>

pretty的简单,但是当我使用:

Pretty simple, but when I use:

@Html.EditorFor(m => m.RememberMe)

我得到一个异常说价值被bassed不能为空:

I get an exception saying the value being bassed cannot be null:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.Boolean'.

我在想什么?好像它应该是直线前进。模型对象在球场上看起来如下:

What am I missing? Seems like it should be straight forward. The field on the model object looks like follows:

[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }

感谢。

更新:如此看来,到底是创建一个空的视图模型对象,并将其传递给视图,而不是让MVC创建一个它自己的事

UPDATE: So it seems that in the end it's a matter of creating an empty view model object and passing it to the view instead of letting MVC create one on it's own.

推荐答案

我不会那样做。如果该值可以为空,我会确保您的编辑器模板有可空布尔的型号。所以你的编辑器模板(在视图中\共享\ EditorTemplates \ Boolean.cshtml)将是:

I would not do it that way. If the value can be null, I would make sure that your editor template has nullable boolean as the model type. So your editor template (in Views\Shared\EditorTemplates\Boolean.cshtml) would be:

@model Boolean?

@Html.CheckBox("", Model.HasValue && Model.Value)

,然后在主视图的剃须刀,你可以有:

And then in the razor of your main view, you could have:

<div class="control-group">
    <div class="controls">
        <label class="checkbox">
            @Html.EditorFor(m => m, new {@class = "checkbox"})
            @Html.LabelFor(m => m)
        </label>
    </div>
</div>

这篇关于MVC 4自定义模板的布尔(剃刀)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:22