How to remove only images which are removed from webpage using Javascript - asp.net-core

In ASP.Net Core MVC. I have created one product CREAT page which allows users to create product and upload multiple images of that product.
Now in editing page of this product I display all these pictures in <div> tag, with javascript of delete function to delete the picture which user want to remove and save the product details again.
From this point I don't understand how to tell ProductController.cs that which images should be deleted from database and which shouldn't.
Can someone put me on right direction, how exactly this process should work?

You can fire jquery call at each image delete; works for smaller set of images
You can store the deleted image-ids in an array and serialize the array to an hidden field and pass the array when you make one jquery call to ProductController.cs on edit submit.
You can check this repository for the solution
https://github.com/rajdeepdebnath/aspnetcore-mvc-collection
My view
#model List<WebApplication4.Controllers.Product>
#{
ViewData["Title"] = "Home Page";
}
#using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
if (Model != null)
{
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Desc</th>
<th>Images</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
var product = Model[i];
var id = $"product[{i}].Id";
var name = $"product[{i}].Name";
var description = $"product[{i}].Description";
<tr>
<td>#product.Id<input type="hidden" value="#product.Id" name='#id' /></td>
<td><input type="text" value="#product.Name" name='#name' /></td>
<td><input type="text" value="#product.Description" name='#description' /></td>
<td>
#foreach (var image in product.ImageIdArr)
{
<span class="image" data-imageid="#image" style="display:inline-block;width:20px;height:20px;background-color:darkseagreen;">😊</span>
}
</td>
</tr>
}
</tbody>
</table>
<input type="hidden" value="[]" name="DeleteImageIdArr" id="DeleteImageIdArr" />
<input type="submit" value="submit" />
}
}
#section Scripts{
<script>
$(document).ready(function () {
$('.image').click(function (v) {
console.log(v);
console.log(v.target.dataset.imageid);
var arr = [];
arr = JSON.parse($('#DeleteImageIdArr').val());
console.log(Array.isArray(arr));
if (arr.indexOf(v.target.dataset.imageid) < 0) {
arr.push(v.target.dataset.imageid);
}
$('#DeleteImageIdArr').val(JSON.stringify(arr))
console.log($('#DeleteImageIdArr').val());
console.log(v.target.hidden);
v.target.hidden = true;
});
$.ajax();
});
</script>
}
My controller
public class HomeController : Controller
{
public IActionResult Index()
{
var products = GetProducts();
return View(products);
}
[HttpPost]
public IActionResult Edit(List<Product> product, string[] DeleteImageIdArr)
{
var products = GetProducts();
return View("Index", products);
}
public List<Product> GetProducts()
{
var products = new List<Product> {
new Product{ Id=1, Name="Test 1", Description="Test 1", ImageIdArr=new int[]{ 1,2,3 } },
new Product{ Id=1, Name="Test 2", Description="Test 2", ImageIdArr=new int[]{ 4,5,6 } },
new Product{ Id=1, Name="Test 3", Description="Test 3", ImageIdArr=new int[]{ 7,8,9 } },
};
return products;
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int[] ImageIdArr { get; set; }
}

Related

Get data from Ajax in ASP.NET Core not working?

I'm new at ASP.NET Core, and this is how I get data from Ajax.
I have a View Model like this
public class RequestSearchDefaultModel
{
public string FromToDate { get; set; }
public int Status { get; set; }
public List<SelectListItem> StatusType { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public IEnumerable<RequestViewModel> requestViewModel { get; set; }
}
When I search the form, I use Ajax to get the data
function OpenSearch() {
var stt = $('#StatusDropDown').val();
var daterange = $('#daterange').val();
var url = "#Url.Action("Search","RequestApproval")";
var model = { FromToDate: daterange, Status: stt };
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
}).done(function (res) {
console.log("here");
$('#myTable').html(res);
})
}
This is controller
[HttpPost]
public async Task<IActionResult> Search([FromBody] RequestSearchDefaultModel m)
{
m.FromDate = DateTime.Parse(m.FromToDate.Substring(0, 10)).Add(new TimeSpan(00, 0, 0));
m.ToDate = DateTime.Parse(m.FromToDate.Substring(14)).Add(new TimeSpan(23, 59, 59));
var request = _headerService.Search();
m.requestViewModel = _mapper.Map<IEnumerable<RequestViewModel>>(request);
return PartialView("_RequestBody", m);
}
This is the view
<div class="card-body">
<div class="table-responsive" id="myTable">
#Html.Partial("_RequestBody")
</div>
</div>
And this is the partial view
#model RequestSearchDefaultModel
<table class="table table-striped">
<thead>
<tr>
<th>Seq.</th>
<th>Title</th>
<th>Status</th>
<th>Draft Date</th>
<th>Final Approval Date</th>
</tr>
</thead>
<tbody id="RequestBody">
#if (Model.requestViewModel == null)
{
}
else
{
foreach (var item in Model.requestViewModel)
{
<tr>
<td>#item.ID</td>
<td>#item.DocumentNo</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ID">#item.Title</a>
</td>
<td>#item.DraftDate</td>
</tr>
}
}
</tbody>
</table>
But I can't get the data, I don't know where I wrong, so please help. Thanks in advance.

Model passed to form in partialview returns with components (that were not null before calling form) being null on form post to controller

I have been trying to find out why submitting a form in my partialview makes some components of my model null. Just before calling the partialview, I have a model with count of AgainstWhoms and TimesPlaces each equal to one.
Even with a simplified partialview where only a column is added, on submitting to the controller, my AgainstWhoms and TimesPlaces collections are now null.
public class ComplaintViewModel
{
[Key]
public int Id { get; set; }
.........
public List<AgainstWhomViewModel> AgainstWhoms { get; set; }
public List<TimesPlacesViewModel> TimesPlaces { get; set; }
public List<WitnessesViewModel> Witnesses { get; set; }
}
public async Task<ActionResult> GetNewComplaint(int intComplainantId)
{
var complaint = new ComplaintViewModel
{
ComplainantId = intComplainantId,
StatusId = 1,
ReceivedDate = DateTime.Now,
AgainstWhoms = new List<AgainstWhomViewModel> { },
TimesPlaces = new List<TimesPlacesViewModel> { },
Witnesses = new List<WitnessesViewModel> { }
};
var newtime = new TimesPlacesViewModel { IncidentDate = DateTime.Today, IncidentLocation = "aaaaaaaaa" };
complaint.TimesPlaces.Add(newtime);
var complainee = new AgainstWhomViewModel { CountryId = 1, Email = "aaaaaaa#yahoo.com"};
complaint.AgainstWhoms.Add(complainee);
..................
return PartialView("_ComplaintFormModal", complaint);
}
Below is my simplified view.
#model ComplaintViewModel
<div>
<form id="Complaintform" asp-controller="Complaint" asp-action="RegisterComplaint" method="post">
<div class="form-row">
<div class="form-group col-lg-8 required">
<label asp-for="ComplaintTitle" class="control-label"></label>
<input type="text" class="form-control" required asp-for="ComplaintTitle">
<span asp-validation-for="ComplaintTitle" class="text-danger"></span>
</div>
</div>
<button type="submit" value="Submit">Submit</button>
</form>
</div>
In my controller post method, newComplaint.AgainstWhom and newComplaint.TimePlaces are now null, while other fields that do not belong to any of the linked lists are returned correctly:
[HttpPost]
public ActionResult RegisterComplaint(ComplaintViewModel newComplaint)
{
..............
You didn't render the TimesPlaces/AgainstWhoms so that data will lose since they are not in form collection .
If you want to edit the TimesPlaces/AgainstWhoms items , you can render like :
#for (int i = 0; i < Model.TimesPlaces.Count; i++)
{
<tr>
<td>
#Html.TextBoxFor(model => model.TimesPlaces[i].IncidentDate)
</td>
<td>
#Html.TextBoxFor(model => model.TimesPlaces[i].IncidentLocation)
</td>
</tr>
}
If you don't want to edit them , you can use hidden field :
#for (int i = 0; i < Model.TimesPlaces.Count; i++)
{
#Html.HiddenFor(model => model.TimesPlaces[i].IncidentDate)
#Html.HiddenFor(model => model.TimesPlaces[i].IncidentLocation)
}
But it's better to avoid that . If you don't want to edit them , i would prefer to query database with ID again for up-to-date records , and avoid posting large data in a request .

partial view not displaying on main view post back

In the main view I am calling a partial view. It work fine for normal usage. On the postback the partial view controller bit is never triggered and the partial view does not displayed. What options are available to make sure that the partial view is rendered even when a postback is triggered.
Model:
public class ReportSummary
{
public int PayrollNumber { get; set; }
public string Name { get; set; }
public string ConflictInterest { get; set; }
public string SummaryConflictInterest { get; set; }
public string FinancialInterest { get; set; }
public string SummaryFinancialInterest { get; set; }
public string GiftInterest { get; set; }
public string SummaryGiftInterest { get; set; }
public string Combined { get; set; }
public string SummaryCombined { get; set; }
}
Controller:
Main:
public ActionResult CoiReporting()
{
...
var model = new ReportParamters();
model.Year = DateTime.Today.Year-1;
model.SelectedTab = "0";
...
return View(model);
}
[HttpPost]
[ActionName("CoiReporting")]
public ActionResult CoiReportingConfrim(string ViewReport, ReportParamters model )
{
...
switch (model.SelectedTab)
{
...
}
return View(model);
}
Partial:
public ActionResult _ReportCriteria(int Year=0, int ReportType=0, int Person=0, int Group=0, int Division=0, int Department=0, int Section=0, string SelectedTab="X")
{
...
var model = new ReportParamters();
model.Year = Year;
model.ReportType = ReportType;
model.Person = Person;
model.Group = Group;
model.Division = Division;
model.Department = Department;
model.Section = Section;
model.SelectedTab = SelectedTab;
return PartialView(model);
}
Views:
Main
#model ConflictOfInterest.Models.ReportParamters
#using (Html.BeginForm("CoiReporting", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.SelectedTab)
#Html.HiddenFor(model => model.Year)
<div id="tabs">
<ul>
<li>Summary</li>
<li>Statistics</li>
<li>Statistics with Person Detail</li>
</ul>
<div id="tabs-1">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
<input type="submit" name="ViewReport" id="ViewReport" value="View Report" class="SaveForm" />
<script type="text/javascript">
$(function () {
var sPath = "";
var sParam = "";
$("#tabs").tabs({
activate: function (event, ui) {
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
....
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.newPanel.load(sPath + sParam);
},
active: $("#SelectedTab").val()
});
});
$('#tabs').click('tabsselect', function (event, ui) {
var selectedTab = $("#tabs").tabs("option", "active");
$("#SelectedTab").val(selectedTab);
});
</script>
}
Partial:
#model ConflictOfInterest.Models.ReportParamters
#{
if (Model.SelectedTab != "0")
{
<table border="0" cellpadding="0" cellspacing="0">
#{
if (Model.SelectedTab == "1")
{
<tr>
<td style="font-weight:bolder">#Html.Label("Year", "Year:")</td>
<td>#Html.DropDownListFor(model => model.Year, Enumerable.Empty<SelectListItem>(), (DateTime.Today.Year - 1).ToString(), new { #style = "width:200px;" })
</td>
<td style="font-weight:bolder">#Html.Label("ReportType", "Report Type:")</td>
<td>#Html.DropDownListFor(model => model.ReportType, new SelectList(ViewBag.ReportType, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">
#Html.Label("Person", "Person:")
#Html.Label("Group", "Group:")
</td>
<td>
#Html.DropDownListFor(model => model.Group, new SelectList(ViewBag.GroupList, "value", "Text"), new { #style = "width:200px;" })
#Html.DropDownListFor(model => model.Person, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })<br />
#Html.TextBox("sPerson")
<input type="button" id="bPerson" value="Search" />
</td>
</tr>
}
/*else
{
<tr>
<td colspan="6"></td>
</tr>
}*/
}
<tr>
<td style="font-weight:bolder">#Html.Label("Division", "Division:")</td>
<td>#Html.DropDownListFor(model => model.Division, new SelectList(ViewBag.Division, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Department", "Department:")</td>
<td>#Html.DropDownListFor(model => model.Department, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Section", "Section:")</td>
<td>#Html.DropDownListFor(model => model.Section, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
</tr>
<tr>
<td colspan="6"></td>
</tr>
</table>
}
else
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
}
}
The activate event of the jquery tab is triggered when a tab is activated(selected).
To ensure that the the same action is taking place on post back you need to use the create event as well.
Take note of the difference in the load at the end
create: function (event, ui) {
//event.preventDefault();
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
//console.log("Start Url: " + sUrl);
sPath = sUrl.substring(0, sUrl.lastIndexOf("?") + 1);
//console.log("Path: "+sPath);
//console.log("Parameters:"+sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length));
sParam = sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length)
var aParam = sParam.split("&");
for (var i = 0; i < aParam.length; i++) {
var aParama = aParam[i].split("=");
switch (i) {
case 7:
aParama[1] = selectedTab;
break;
}
aParam[i] = aParama.join("=");
}
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.panel.load(sPath + sParam);
},

Asp .net MVC...HttpPostedFileBase uploadImage is not always null

I want upload an Image but it always gets null. I'm using HttpPostedFileBase.
This is my COntroller
public ActionResult EmployeeDetail(EmployeeModel employee, HttpPostedFileBase UploadImage)//this UploadImage Object is always null
{
EmployeeModel employeeModel = new EmployeeModel();
if (string.IsNullOrEmpty(employeeModel.Name))
{
ModelState.AddModelError("Name", "Name is Required");
}
employeeModel.Name = employee.Name;
if (string.IsNullOrEmpty(employeeModel.DOJ))
{
ModelState.AddModelError("DOJ", "DOJ is Requird");
}
employeeModel.DOJ = employee.DOJ;
if (string.IsNullOrEmpty(employeeModel.DOB))
{
ModelState.AddModelError("DOB", "DOB is Required");
}
employeeModel.DOB = employee.DOB;
if (string.IsNullOrEmpty(employeeModel.Designation))
{
ModelState.AddModelError("Designation", "Designation is required");
}
employeeModel.Designation = employee.Designation;
string ImageName = Path.GetFileName(UploadImage.FileName);
string Physicalpath = Server.MapPath("~/images/" + ImageName);
UploadImage.SaveAs(Physicalpath);
employee.UploadImage = Physicalpath;
//string ImageName = Path.GetFileName(image.FileName);
//string physicalPath = Server.MapPath("~/images/" + ImageName);
//image.SaveAs(physicalPath);
// ModelState.AddModelError("UploadImage", "upload is required");
//employee.UploadImage = physicalPath;
EmployeeBusinessLayer employeeBL = new EmployeeBusinessLayer();
employeeBL.InsertDataRegistration(employeeModel);
return RedirectToAction("Index");
}
This is my View
#using (Html.BeginForm("EmployeeDetail", "Home", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" })) //i have used all the codes which could be need to make it work...still not working
{
<div class="MainDiv">
<table class="Table">
<tr class="Row">
<td class="Column1"> Name</td>
<td class="Column2">#Html.TextBoxFor(model => model.Name) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DOJ </td>
<td class="Column2">#Html.TextBoxFor(model => model.DOJ, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name) </td>
</tr>
<tr class="Row">
<td class="Column1">DOB</td>
<td class="Column2">#Html.TextBoxFor(model => model.DOB, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DESIGNATION</td>
<td class="Column2">#Html.TextBoxFor(model => model.Designation) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">UPlOAD </td>
<td class="Column2">#Html.TextBoxFor(model => model.UploadImage, new { #type = "File" })
</td>
</tr>
<tr class="Row">
<td colspan="2">
<input type="submit" class="button" name="submit" value="Submit">
<input type="reset" class="button1" value="Clear" name="Clear">
</td>
</tr>
</table>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/jquery-1.8.3.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/ui/minified/jquery-ui.custom.min.js"></script>
<script type="text/javascript">
$(function () {
// This will make every element with the class "date-picker" into a DatePicker element
$('.datepicker').datepicker();
})
</script>
</div>
}
this is my Model
public Model
{
public int EmployeeId { get; set; }
[Required(ErrorMessage = "this is required")]
public string Name { get; set; }
[Required (ErrorMessage = "This is required")]
public string DOJ { get; set; }
[Required(ErrorMessage ="This is required")]
public string DOB { get; set; }
[Required(ErrorMessage ="This is required")]
public string Designation { get; set; }
[Required(ErrorMessage = "This is required")]
public string UploadImage { get; set; }
public HttpPostedFileBase MyFile { get; set; }
}
I don't see anywhere you are passing any parameter to EmployeeDetail(). Are you able to get data for your EmployeeModel? If yes, then that at least confirm that your view able to call the EmployeeDetail() action.
Next, you need to make sure you are passing proper parameter to your EmployeeDetail(). One of the way I could think of is to use ajax. So you can create an ajax call when submit button is clicked, and pass all your data and the uploaded file input in the ajax method.
This is an example of using ajax call with JQuery syntax to pass data to the action
var inputFiles = $('inpFile').val();
var actMethod = "#Url.Action("EmployeeDetail", "Index")"
var postData = {
"Name": $('inpName').val(),
"DOJ": $('inpDOJ').val(),
...
"UploadImage": inputFiles
}
$.ajax()
{
url: actMethod ,
data: postData,
type: "POST",
success: function (data) {
alert("Insert Successful!");
}
}

Saving multiple records on submit click into differnt entities in MVC4. Not getting values from view in Controller

I am trying to save the class attendance for multiple students on click of submit button. I am able to create the blank records in the concern tables and then populate the data in view.
I have the following view model:
public class TeacherAttendanceModel
{
#region Required Properties
public long ScholarAttendanceId { get; set; }
public string Student { get; set; }
public bool Absent { get; set; }
public string AbsentComment { get; set; }
public bool Uniform { get; set; }
public bool Homework { get; set; }
public string HomeworkComment { get; set; }
public String UniformCommentSelected { get; set; }
public IEnumerable<String> UniformComment { get; set; }
#endregion
}
My Controller is as below.
public class TeacherAttendanceController : Controller
{
//
// GET: /TeacherAttendance/
public ActionResult Index()
{
long classId = Success.Business.Roles.Teacher.GetHomeRoomClassID(Convert.ToInt64(Session[GlobalVar.LOGGED_IN_ID]));
var classAttendanceStatus = Success.Business.Entities.ClassAttendance.GetClassAttendanceStatus(classId);
ViewBag.status = classAttendanceStatus;
var attendanceData = TeacherAttendance.CreateClassAttendance(classId);
return View(attendanceData);
}
[HttpPost]
public ActionResult Index(IEnumerable<TeacherAttendanceModel> teacherAttendanceModel)
{
try
{
if (ModelState.IsValid)
{
TeacherAttendance.SaveAttendance(teacherAttendanceModel);
}
}
catch (Exception e)
{
}
return View(teacherAttendanceModel);
}
}
Get Index is working fine. But I am not getting the TeacheAttendanceModel object in Post index. I get null object. I would be thank full to get any help in this regards. How to update the multiple records of attendance on submit click?
I am using the following View:
#foreach (var item in Model) {
<tr >
<td style="border-style:solid; border-color:darkslategray; border-width:thin;">
#Html.DisplayFor(modelItem => item.Student)
</td>
<td style="border-style:solid; border-color:darkslategray; border-width:thin;">
#Html.CheckBoxFor(modelItem => item.Absent, ViewBag.status == 2 ? new {disabled = "disabled"} : null)
#Html.TextBoxFor(modelItem => item.AbsentComment, ViewBag.status == 2 ? new {disabled = "disabled"} : null)
</td>
<td style="border-style:solid; border-color:darkslategray; border-width:thin;">
#Html.CheckBoxFor(modelItem => item.Uniform, ViewBag.status == 2 ? new {disabled = "disabled"} : null)
#Html.DropDownListFor(modelItem => item.UniformCommentSelected, new SelectList(item.UniformComment),item.UniformCommentSelected ?? "---Select---", ViewBag.status == 2? new {disabled = "disabled"} : null)
</td>
<td style="border-style:solid; border-color:darkslategray; border-width:thin;">
#Html.CheckBoxFor(modelItem => item.Homework, ViewBag.status == 2 ? new {disabled = "disabled"} : null)
#Html.TextBoxFor(modelItem => item.HomeworkComment, ViewBag.status == 2? new {disabled = "disabled"} : null)
</td>
</tr>
}
Model:
public class Test
{
public List<string> UniformComment { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new Test
{
UniformComment = new List<string>{ "one", "two", "three" }
};
return View(model);
}
[HttpPost]
public ActionResult Index(Test model)
{
return View(model);
}
View:
#using (Html.BeginForm())
{
for (var i = 0; i < Model.UniformComment.Count; i++)
{
#Html.TextBoxFor(x => Model.UniformComment[i])
}
<input type="submit" value="Save" />
}
Rendered html example:
<input id="UniformComment_0_" name="UniformComment[0]" type="text" value="one" />
<input id="UniformComment_1_" name="UniformComment[1]" type="text" value="two" />
<input id="UniformComment_2_" name="UniformComment[2]" type="text" value="three" />
The idea is iterate with for loop or create EditorTemplate and then you receive indexed items.
Added (Feel the difference):
View:
#using (Html.BeginForm())
{
foreach (var comment in Model.UniformComment)
{
#Html.TextBoxFor(x => comment)
}
<input type="submit" value="Save" />
}
Rendered html:
<input id="comment" name="comment" type="text" value="one" />
<input id="comment" name="comment" type="text" value="two" />
<input id="comment" name="comment" type="text" value="three" />
Use a IList instead of IEnumerable in the view and replace the foreach loop with a for loop.
Step 1:
Use
#model IList<TeacherAttendanceModel>
instead of
#model IEnumerable<TeacherAttendanceModel>
Step 2:
Use
#for (var i = 0; i < Model.Count; i++)
instead of
#foreach (var item in Model)
Refer How to pass IEnumerable list to controller in MVC including checkbox state? for more details.