Checkbox list in Asp.net MVC example

Here is an example of how you can use checkbox list in asp.net mvc razor, also you learn how you can add text with hyperlink in Checkbox list control in asp.net mvc application.

Bind ASP.NET CheckBoxList and get selected Items when form submitted C# example. How to use CheckBoxList in asp.net c#.

What problem are we solving here?
We want to create a checkbox list where each item in the list will be linked to some page, so before user tick some item from checkbox list they can also check the item details at the same page. Finally when the form is submitted we need to capture the selected item values

Step 1: Create two properties in Model one string list and one SelectListItem list

public class ContactModel
{
public List<string> SelectedSubjects { get; set; } 
public List<SelectListItem> SubjectList { get; set; } }

Step 2: Capture the selected item values in controller code.
Code in Controller (while posting the form)

[HttpPost]
public ActionResult postOneToOneTrainingReq(ContactModel model)
{
foreach (string s in model.SelectedSubjects)
{
_str.Append(string.Format("{0} <br>", s));
}
//or
model.SelectedSubjects.ToString();
}

Step 3:
Now create a string list either in razor or in some utility file.

List<Subject> subjectList = new List<Subject>();      
subjectList.Add(new Subject() { Name = "JavaScript", Value="Java Script" });
subjectList.Add(new Subject() { Name = "Asp.Net", Value="Asp.Net"  });
subjectList.Add(new Subject() { Name = "Asp.Net MVC", Value=".Net MVC" });
subjectList.Add(new Subject() { Name = "Web API", Value=".Net API" });

Step 4: Now create the form where for each item there will be a checkbox and the text will be linked to some page.

@using (Html.BeginForm("actionName", "home", FormMethod.Post))
{
@foreach (Subject s in subjectList)
{ <div>
<input type="checkbox" name="SelectedSubjects" value="s.Name" />
<a href="ur-url">@s.Name</a>
        </div>  
        <input type="submit" value="Submit" />     
    }
}

When form is submitted check the values in “SelectedSubjects” property, all selected item will be captured.

Hope this helped you
 
Checkbox list with Hyperlink in Asp.net MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial