aditya
aditya

Reputation: 595

How to store multiple checkbox values in model and render them in view and controller in mvc4?

I am using ASP.NET MVC5 in my application. I want to show languages known by an employee using check boxes in my view(check boxes with same name). For this how to write my model, pass them from the controller and display them in the view?

I have those vales stored in an Enum

public enum Language {
    English=1,
    Telugu=2,
    Hindi=3,
    Spanish=4
}

It is ok if I have to store them in a table in DB.

Upvotes: 1

Views: 1041

Answers (1)

Ivan Yurchenko
Ivan Yurchenko

Reputation: 3871

You can use the CheckBoxListFor helper:

 @Html.CheckBoxListFor(model => model.SelectedOptions, Model.AllOptions)

And your model would look like this:

public class MyModel {

    // This property contains the available options
    public SelectList AllOptions { get; set; }

    // This property contains the selected options
    public IEnumerable<string> SelectedOptions { get; set; }

    public MyModel() {
        AllOptions = new SelectList(
            new[] { "Option1", "Option2", "Option3" });

        SelectedOptions = new[] { "Option1" };
    }
}

In controller you just simply pass your model to the View:

[HttpGet]
[ActionName("Index")]
public ActionResult Index()
{
     var model = new MyModel();
     return View(model);
}

You can change the AllOptions and SelectedOptions properties as you want (just remove the code from the constructor of MyModel and place it in your controller class).

For more details check this out, there is a note about how to work with Enum: CheckBoxList for Enum types MVC Razor.

Upvotes: 1

Related Questions