我有一个这样的模型:
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
保存模型,或者保存属性Employer
和Position
未选中该复选框。
我怎样才能实现这一点,模型绑定器是否适合我? 谢谢你提前。
答案 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();
}