2017-06-04 73 views
2

視圖模型的特定屬性我有一個這樣的模型: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沒有被檢查。

我該如何做到這一點,模型活頁夾能幫我嗎? 謝謝先進。

+0

您的視圖模型有IsAutonomous? – User3250

+0

沒有。這只是CheckBox – user70014

+0

將其添加到視圖模型中,並將其用於數據的條件綁定。或者使用jquery啓用禁用複選框被選中或取消選中的字段。已禁用的字段數據不會發布到操作。恕我直言,ViewModel方式更容易實現。 – User3250

回答

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