0

I wanna send checkboxes value from View to Action with viewmodel.

Can you help me ؟

I'm sorry about my terrible English

2
  • 1
    Please provide example code you have so far. Describing a specific issue is more helpful. Are you having problems posting the checkbox values to your controller? What is the view currently sending when you submit? Commented Aug 24, 2021 at 22:39
  • Hello @mr lemon did you tried the solution? Commented Sep 10, 2021 at 1:46

1 Answer 1

1

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 the plan 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:

enter image description here

Hope it would guide you through.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.