'mvc - Bind specific properties of ViewModel based on CheckBox

I have a model like this:

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

In the view I have:

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

and so on for the different properties.

The controller is very basic:

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

I want to save the model with the property AutonomousActivity only if the user clicked the checkbox IsAutonomous, or save the properties Employer and Position if the checkbox is not checked.

How can I achieve that, does the model binder do that for me?



Solution 1:[1]

 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

}

Controller:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asif Raza