将@ Html.CheckBoxFor添加到asp.net mvc 4

时间:2013-05-27 07:17:52

标签: asp.net-mvc asp.net-mvc-4

我的反馈表中有复选框,看起来像是 enter image description here
我在模型中添加了复选框

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

添加到我的控制器

    [HttpGet]
    public ActionResult CareerForm()
    {
        CareerForm model = new CareerForm();

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

        return View(model);
    }

但是我需要在电子邮件中添加选中的复选框,但我不知道该怎么做 我试过了

 public ActionResult CareerForm(CareerForm Model, HttpPostedFileBase Resume)
    {
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.BodyEncoding = Encoding.UTF8;
        string message = //...
                         "Type: " + Model.EmploymentType;
        msg.Body = message;

    //....
    }

但是我的电子邮件中只有文字类型:System.Collections.Generic.List`1 [CheckBoxes]
如何让它正常工作?

3 个答案:

答案 0 :(得分:1)

您的model.EmploymentTypeList<CheckBoxes>

model.EmploymentType = new List<CheckBoxes>

您必须使用索引访问它的值。您正在转换为字符串 一个System.Collection.Generic.

答案 1 :(得分:1)

类似于以下内容

string message = "Type: ";

foreach(var item in Model.EmploymentType)
{
    if (item.Checked)
        message += item.Text;
}

答案 2 :(得分:1)

您需要从列表中的每个选中复选框中获取文本值。

这是一个清单:

model.EmploymentType = new List<CheckBoxes>...

你想要检查的那些:

var checked = model.EmploymentType.Where(x => x.Checked);

然后你需要这些框中的Text属性:

string message = "Type: " + checked.Text;

将它放在你的控制器动作中,我希望它看起来像这样:

public ActionResult CareerForm(CareerForm Model, HttpPostedFileBase Resume)
{
    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
    msg.BodyEncoding = Encoding.UTF8;
    string message = "Type: ";
    foreach(var box in Model.EmploymentType.Where(x => x.Checked)) {
        message += box.Text + " ";
    }
    msg.Body = message;
}