C# MVC 4 bool 的自定义模板(剃刀)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14425994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:45:48  来源:igfitidea点击:

MVC 4 Custom template for bool (razor)

c#.netasp.net-mvcrazor

提问by Tyrel Van Niekerk

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:

我正在使用 twitter bootstrap 框架,因此为了让 EditorFor 和 DisplayFor 方法输出我需要的内容,我为每种类型(如字符串、文本、密码等)创建了自定义模板。对于我的登录页面,我想要一个 RememberMe bool,所以和以前一样,我创建了以下模板并将其放入 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 simple, but when I use:

很简单,但是当我使用:

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

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; }

Thanks.

谢谢。

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.

更新:所以看起来最终创建一个空的视图模型对象并将其传递给视图而不是让 MVC 自己创建一个。

采纳答案by Jonathan

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:

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

@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>

回答by Sampath

You have to initialize your RememberMebool valueinside the constructor as shown below.

您必须RememberMebool value在构造函数内部初始化,如下所示。

Remember that using uninitialized variables in C# is not allowed.

请记住,不允许在 C# 中使用未初始化的变量。

using System.ComponentModel; 

public class ClassName
 {    
   public ClassName ()
        {
            RememberMe = false;
        }

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

For more infromation check Default Values Table

有关更多信息,请查看默认值表

I hope this will help to you.

我希望这会对你有所帮助。

回答by Tyrel Van Niekerk

Reading the responses so far, I started wondering about how the model object was being initialized. So this is rather weird, but I found the answer. Hopefully someone can explain the weirdness. Might be how MVC initializes a model object if you don't specify one.

阅读到目前为止的响应,我开始想知道模型对象是如何初始化的。所以这很奇怪,但我找到了答案。希望有人能解释这种奇怪之处。如果您不指定一个模型对象,这可能是 MVC 初始化模型对象的方式。

The default MVC Internet template has the following for the Login action:

默认的 MVC Internet 模板具有以下用于登录操作的内容:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;

    return View();
}

That gives the error. Changing it to the following however, fixes the problem:

这给出了错误。但是,将其更改为以下内容可以解决问题:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    var loginModel = new LoginModel();

    ViewBag.ReturnUrl = returnUrl;

    return View(loginModel);
}

So this answers the question on how to solve the problem, but still leaves the reason unresolved. Could it be because MVC creates an instance of the object in a different way, say with reflection or something?

所以这回答了如何解决问题的问题,但仍然没有解决原因。可能是因为 MVC 以不同的方式创建了对象的实例,比如使用反射或其他方式?

回答by Shane Dutchie

You could change your model so it accepts the null values as "yes"/"no"

您可以更改模型,使其接受空值作为“是”/“否”

public bool? RememberMe { get; set; }