Reputation:
I wanna send checkboxes value from View to Action with viewmodel.
Can you help me ؟
I'm sorry about my terrible English
Upvotes: 0
Views: 1309
Reputation: 22447
You could try this way to achieve your requirements
View Model:
public class CheckBoxViewModel
{
public List<Plans> plans { get; set; }
}
public class Plans
{
public int PlanId { get; set; }
public string PlanName { get; set; }
public bool IsSelected { get; set; }
}
Controller When Load View Model:
public IActionResult LoadCheckBoxFromViewModel()
{
var plan = new List<Plans>()
{
new Plans(){ PlanName = "Plan A",PlanId =1, IsSelected= false},
new Plans(){ PlanName = "Plan B",PlanId =2, IsSelected= false},
new Plans(){ PlanName = "Plan C",PlanId =3, IsSelected= false},
new Plans(){ PlanName = "Plan D",PlanId =4, IsSelected= false}
};
var model = new CheckBoxViewModel();
model.plans = plan;
return View(model);
}
Note: I have loaded the
checkbox
with few predefined value to check. If you need a single checkbox so you can simply customize it as per your requirement. In that case you don't need to loop through theplan
checkbox list.
View Of LoadCheckBoxFromViewModel Controller:
@model CheckBoxViewModel
@{
ViewData["Title"] = "LoadCheckBoxFromViewModel";
}
<h4>Load CheckBox From ViewModel</h4>
<h4>Submit value to Controller</h4>
<hr />
@using (Html.BeginForm("GetValueFromCheckBoxUsingViewModel", "StackOverFlow"))
{
for (int i = 0; i < Model.plans.Count; i++)
{
@Html.CheckBoxFor(r => Model.plans[i].IsSelected)
<label> @Model.plans[i].PlanName</label>
@Html.HiddenFor(h => @Model.plans[i].PlanId)
@Html.HiddenFor(h => @Model.plans[i].PlanName)
}
<input id="Button" type="submit" value="Save" class="btn btn-primary" />
}
Controller When Submit Checkbox:
[HttpPost]
public IActionResult GetValueFromCheckBoxUsingViewModel(CheckBoxViewModel checkBoxViewModel)
{
return View(checkBoxViewModel);
}
Output:
Hope it would guide you through.
Upvotes: 1