asp.net mvc @Html.CheckBoxFor [英] asp.net mvc @Html.CheckBoxFor

查看:30
本文介绍了asp.net mvc @Html.CheckBoxFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有复选框

I have checkboxes in my form

我在我的模型中添加了

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;

 namespace CorePartners_Site2.Models
 {
public class CareerForm
     {
    //....
    public List<CheckBoxes> EmploymentType { get; set; } 
      }
 }

 public class CheckBoxes
 {
     public string Text { get; set; }
     public bool Checked { get; set; }
 }

并添加到我的表单中

@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_1" })
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_2" })
@Html.CheckBoxFor(model => model.EmploymentType, new { id = "employmentType_3" })

但我弄错了

怎么了?

推荐答案

CheckBoxFor 接受一个 bool,你传递的是一个 List代码>到它.你需要做:

CheckBoxFor takes a bool, you're passing a List<CheckBoxes> to it. You'd need to do:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.DisplayFor(m => m.EmploymentType[i].Text)
}

注意我也为 Text 属性添加了一个 HiddenFor ,否则当你发布表单时你会丢失它,所以你不会知道哪些项目你检查过了.

Notice I've added a HiddenFor for the Text property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.

编辑,如您的评论所示,您的 EmploymentType 列表在提供视图时为 null.您还需要通过在您的操作方法中执行此操作来填充它:

Edit, as shown in your comments, your EmploymentType list is null when the view is served. You'll need to populate that too, by doing this in your action method:

public ActionResult YourActionMethod()
{
    CareerForm model = new CareerForm();

    model.EmploymentType = new List<CheckBox>
    {
        new CheckBox { Text = "Fulltime" },
        new CheckBox { Text = "Partly" },
        new CheckBox { Text = "Contract" }
    };

    return View(model);
}

这篇关于asp.net mvc @Html.CheckBoxFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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