user2761009
user2761009

Reputation: 85

Get selected checkboxes on form post ( c# razor)

I am adding checkboxes to html using foreach.

@foreach (var item in list)
{
    <input type="checkbox" name="@item.Value" value="@item.Value" />
    @item.Value
}

I need to get values from selected on form post. Thanks in advance.

Upvotes: 1

Views: 1600

Answers (2)

Shyju
Shyju

Reputation: 218862

You can use EditorTemplates to handle this.

For example, You want to create a student creation screen where you need to provide check boxes for course selection, you will create a viewmodel like this

public class CreateStudentVM
{        
    public string Name { set; get; }      
    public List<CourseSelection> Courses { set; get; }

    public CreateStudentVM()
    {
        this.Courses=new List<CourseSelection>();
    }
}
public class CourseSelection
{
    public int CourseId { set; get; }
    public string CourseName { set; get; }
    public bool IsSelected { set; get; }
}

and in your GET action method,you create an object of CreateStudentVM class,initialize the Courses property with a list of courses (for the checkbox items)

private List<CourseSelection> GetCourses()
{
    //Hard coded for demo. Replace with entries from db
    return new List<CourseSelection>()
    {
        new CourseSelection {CourseId = 1, CourseName = "CS"},
        new CourseSelection {CourseId = 2, CourseName = "MT"}
    };
}

public ActionResult Index()
{
    var vm = new CreateCustomerVM();
    vm.Courses = GetCourses();
    return View(vm);
}

Now we need to create an Editor template. Go to the Views folder,Select the directory for your current controller and add a subfolder called EditorTemplates. Add a partial view under that called CourseSelection.cshtml

enter image description here

Now Add the below code the new partial view we created.

@model YourNamespaceHere.CourseSelection
<div>
    @Model.CourseName
    @Html.CheckBoxFor(s=>s.IsSelected)
    @Html.HiddenFor(s => s.CourseId)
</div>

The name of the editortemplate partial view should be same as the type we are using to bind to it (in this case CourseSelection)

Now we will use Html.EditorFor helper method in the main view which is strongly typed to CreateStudentVM

@model YourNamespaceHere.CreateStudentVM
@using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Name)

    @Html.EditorFor(s=>s.Courses)

    <input type="submit"/>
}

This should render your page with checkboxes for each items in the Courses collection. When you post your form back, you can check the IsSelected property of Courses collection.

[HttpPost]
public ActionResult Index(CreateStudentVM model)
{
    if (model != null)
    {
        // TO DO : Save and Redirect
        // PRG Pattern
    }
    return View(model);
}

enter image description here

Cheers !

Upvotes: 0

beautifulcoder
beautifulcoder

Reputation: 11340

Really, the best way would be to use the helper:

@for (var i = 0; i < list.Length; i++)
{
    @Html.Checkbox("item[" + i + "]")
    @list[i].Value
}

In the controller, make sure to bind to a list of items:

[HttpPost]
public ActionResult Index(IEnumerable<bool> item) {}

Hope that helps.

Upvotes: 1

Related Questions