Asp.net mvc mvc-基于复选框绑定ViewModel的特定属性
我有一个这样的模型:Asp.net mvc mvc-基于复选框绑定ViewModel的特定属性,asp.net-mvc,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
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>
问题是:仅当用户单击复选框IsAutonomous
时,我才想使用属性AutonomousActivity
保存模型,或者如果未选中复选框,则保存属性Employer
和Position
我如何才能做到这一点,模型绑定器是否为我做到了这一点?
提前谢谢
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();
}
在ViewModel中是否有IsAutonomous?否。这只是复选框将其添加到ViewModel中并用于数据的条件绑定。或者使用jquery在选中或取消选中复选框时启用或禁用字段。禁用的字段数据不会过帐到操作。IMHO ViewModel方式更易于实现。jQuery已运行。谢谢伟大的若使用jquery方式,则不应将viewmodel方式标记为答案。只需在代码中不使用它的情况下向上投票即可。:)
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();
}