mvc - 基于CheckBox

时间:2017-06-04 03:55:34

标签: asp.net-mvc

我有一个这样的模型:

 public class EmploymentVM
{
    public string EmploymentType { get; set; }
    public string Employer { get; set; }
    public string Position { get; set; }
    public double GrossMonthlyIncome { get; set; }
    public DateTime? StartDate { get; set; }
    public string AutonomousActivity { get; set; }
}

在视图中我有:

                <div class="form-group">
                    @Html.LabelFor(x => x.Employer)
                    @Html.TextBoxFor(x => x.Employer, new { @class = "form-control required" })
                </div>
                <div class="form-group">
                    @Html.LabelFor(x => x.Position)
                    @Html.TextBoxFor(x => x.Position, new { @class = "form-control required" })
                </div>
                <div class="form-group">
                    @Html.LabelFor(x => x.GrossMonthlyIncome)
                    @Html.TextBoxFor(x => x.GrossMonthlyIncome, new { @class = "form-control required digits" })
                </div>

依此类推不同的属性。

控制器非常基本:

[HttpPost]
    public ActionResult EmploymentInfo(EmploymentVM vm)
    {
        //the actual code to save employment
        return View();
    }

问题是:我希望仅在用户点击复选框AutonomousActivity时使用属性IsAutonomous保存模型,或者保存属性EmployerPosition未选中该复选框。

我怎样才能实现这一点,模型绑定器是否适合我? 谢谢你提前。

1 个答案:

答案 0 :(得分:0)

 public class EmploymentVM
 {
public string EmploymentType { get; set; }
public string Employer { get; set; }
public string Position { get; set; }
public double GrossMonthlyIncome { get; set; }
public DateTime? StartDate { get; set; }
public string AutonomousActivity { get; set; }
public bool IsAutonomous { get; set; } //add in viewmodel bind it with checkbox

}

控制器:

 public ActionResult EmploymentInfo(Employments vm)
{
   if(vm.IsAutonomous) {
    // you can set the value null/empty to any property
      vm.Employer =null;

    //save it 
   }
   else {
        // if checkbox is not checked
       //save it 
    }

    return View();
}