How to get a checkbox value in mvc 4 and save to database
i want to get a checkbox value in mvc 4 and save that value in database .
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
MayankRank #4,018 · 371 reputationPosted Jan 2, 2017, 11:08 PM EST
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ValidationsMvc.Models
{
public class CheckBoxClass
{
public List
public List
public string LocationList { get; set; }
public string UserList { get; set; }
}
public class Users
{
public int Id { get; set; }
public string UserName { get; set; }
}
public class Location
{
public int Id { get; set; }
public string LocationName { get; set; }
}
}
Controller code:
public ActionResult CheckBoxListSelection()
{
var user = new Users
{
Id= 1,
UserName = "A"
};
var user2 = new Users
{
Id = 2,
UserName = "B"
};
var user3 = new Users
{
Id = 3,
UserName = "C"
};
List
list.Add(user);
list.Add(user2);
list.Add(user3);
var loc = new Location
{
Id = 1,
LocationName = "UP"
};
var loc2 = new Location
{
Id = 2,
LocationName = "Delhi"
};
var loc3 = new Location
{
Id = 3,
LocationName = "Bihar"
};
List
lst.Add(loc);
lst.Add(loc2);
lst.Add(loc3);
var model = new CheckBoxClass
{
Usr = list,
Loc=lst
};
return View(model);
}
[HttpPost]
public ActionResult CheckBoxListSelection(CheckBoxClass model)
{
//Here you will get the location and user in list u can split it by split function and save in DB
return RedirectToAction("CheckBoxListSelection");
}
View:
@model ValidationsMvc.Models.CheckBoxClass
@*~/Models/CheckBoxClass.cs*@
@{
ViewBag.Title = "CheckBoxListSelection";
}
CheckBoxListSelection
@using (Html.BeginForm("CheckBoxListSelection", "Home", FormMethod.Post))
{
@foreach (var items in Model.Usr as List
{
@items.UserName
}
@Html.HiddenFor(M => M.UserList, new { id = "userIdLst" })
@foreach (var items in Model.Loc as List
{
@items.LocationName
}
@Html.HiddenFor(M => M.LocationList, new { id = "locIdLst" })
}
If this resolve your issue please mark as answer
Mangesh GRank #294 · 8.6K reputationPosted Jan 2, 2017, 2:39 AM EST
Can u post the code Shubham an what difficulty u are facing please
Ahmed AbdiRank #1,099 · 1.7K reputationPosted Jan 2, 2017, 5:03 AM EST
Anoop Kumar SharmaRank #127 · 17.4K reputationPosted Jan 2, 2017, 7:05 AM EST