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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
MayankPosted Jan 3, 2017, 4:08 AM
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
Anoop Kumar SharmaPosted Jan 2, 2017, 12:05 PM
Ahmed AbdiPosted Jan 2, 2017, 10:03 AM
Mangesh GPosted Jan 2, 2017, 7:39 AM
Can u post the code Shubham an what difficulty u are facing please