2

我想在 ASP.net MVC 中将一个复选框绑定到一个整数(如下所示的 ISACTIVE 值)。

@Html.CheckBoxFor(model => model.ISACTIVE, new { htmlAttributes = new { @class = "form-control" } })

我知道 Html.CheckBoxFor 只接受 bool 作为输入,我可以在我的模型上添加一个新属性,但我使用的是已经存在的数据库,每次更新时,模型都会刷新。

有没有办法为 CheckBoxFor 创建一个新方法,该方法将根据复选框是否被选中返回一个整数?

4

4 回答 4

1

您也可以尝试input对复选框类型使用简单的 HTML 控件。这样,您可以为其分配一些值或名称,并将其返回给控制器。

这可能不是您想要实现的确切目标。不过,它会给你一个想法。

在您看来:

<input type="checkbox" id="yourId" name="selectedIds" value="@menu.Id"/>

在您的控制器中,您可以尝试访问此特定控件的值,如下所示:

value = Request.Form["selectedIds"];

希望这可以帮助。

于 2015-04-20T09:27:47.730 回答
0

将 bool 属性添加到模型中:

public bool BoolValue
{
    get { return IntValue == 1; }
    set { IntValue = value ? 1 : 0;}
}

public int IntValue { get; set; }

编辑:

您还可以手动创建复选框控件:

@Html.CheckBox("IsActive", Model.IsActive ?  true : false,  new { htmlAttributes = new { @class = "form-control" } }) 

如果名称与 MVC 先前生成的名称匹配,则该值应返回到控制器操作。也许您必须定义自己的自定义值提供程序才能从 bool 转换为 int,类似于:How to map a 1 or 0 in an ASP.Net MVC route segment into a Boolean action method input parameter

于 2015-04-20T09:15:20.693 回答
0

选项1

既然您无法向实体添加新属性,为什么不检查操作中的 bool 值呢?

public ActionResult Test(bool isActive)
{

    int test = isActive ? 1 : 0;


    return View();
}   

选项 2

创建您自己的视图模型来检查布尔值,然后创建一个新的实体记录。

模型

public class NikolsModel
{

    [Required]
    public bool IsActive { get; set; }

    // Other Properties...

}

行动

    public async Task<ActionResult> Index(NikolsModel model)
    {

        if (ModelState.IsValid)
        {
            //
            // Create a new instance of your entity 
            //
            var record = new NikolsEntity
            {
                IsValid = model.IsActive ? 1 : 0,
                //Other properties from model
            };

            DbContext.NikolsEntity.add(record);

            await DbContext.SaveChangesAsync();

            return RedirectToAction("Index");
        }


        //Something went wrong, return the view with model errors
        return View(model);

    }
于 2015-04-20T09:25:26.603 回答
0
@Html.CheckBoxFor(model => model.Modelname)

然后,在您的控制器中:

var isChecked = Request.Form["Modelname"];

if(!isChecked.Equals("false"))
{
//Checkbox is checked, do whatever you want!

}
于 2015-08-20T08:49:44.047 回答