我怎样才能让Html.CheckBoxFor()上的绳子领域的工作? [英] How can I make Html.CheckBoxFor() work on a string field?

查看:282
本文介绍了我怎样才能让Html.CheckBoxFor()上的绳子领域的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC3剃刀和C#。我提出各种各样的表单生成器,所以我有一个具有下列对象的集合模型:

I'm using ASP.NET MVC3 with Razor and C#. I am making a form builder of sorts, so I have a model that has a collection of the following object:

public class MyFormField
{
    public string Name { get; set; }
    public string Value { get; set; }
    public MyFormType Type { get; set; }
}

MyFormType就是这样告诉我,如果表单域是一个复选框,或文本框,或上传文件,或任何一个枚举。我的编辑模板看起来是这样的(见注释):

MyFormType is just an enum that tells me if the form field is a checkbox, or textbox, or file upload, or whatever. My editor template looks something like this (see the comment):

〜/查看/ EditorTemplates / MyFormField.cshtml

@model MyFormField
@{
    switch (Model.Type)
    {
        case MyFormType.Textbox:
            @Html.TextBoxFor(m => m.Value)
        case MyFormType.Checkbox:
            @Html.CheckBoxFor(m => m.Value)  // This does not work!
    }
}

我试过铸造/转换 m.Value 来一个布尔在拉姆达前pression为CheckBoxFor(),但抛出一个错误。我只想手动构建一个复选框输入,但是CheckBoxFor()似乎做两件事情,我似乎无法复制:

I tried casting/converting the m.Value to a bool in the lambda expression for CheckBoxFor(), but that threw an error. I would just manually construct a checkbox input, but CheckBoxFor() seems to do two things that I can't seem to replicate:


  1. 创建一个以某种方式得到由复选框填充一个隐藏的输入。这似乎是什么模型绑定拾取。

  2. 生成的名称构成了对象,以使模型绑定获取值到合适的物业。

有谁知道围绕一个字符串,还是有办法使用CheckBoxFor()来手动复制它的功能,这样我就可以使这项工作的方式?

推荐答案

您也可以在您的视图模型添加属性:

You could also add a property on your viewmodel:

    public class MyFormField
    {
        public string Name { get; set; }
        public string Value { get; set; }

        public bool CheckBoxValue
        {
            get { return Boolean.Parse(Value); }
        }

        public MyFormType Type { get; set; }
    }

您的看法是这样的:

@model MyFormField
@{
    switch (Model.Type)
    {
        case MyFormType.Textbox:
            @Html.TextBoxFor(m => m.Value)
        case MyFormType.Checkbox:
            @Html.CheckBoxFor(m => m.CheckBoxValue)  // This does work!
    }
}

使用Boolean.TryParse如果你想避免的异常。

Use Boolean.TryParse if you want to avoid exceptions.

这篇关于我怎样才能让Html.CheckBoxFor()上的绳子领域的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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