I have referred this question to learn how to post the checkbox
selected values in the database.
However, I am not able to get my selected
values on debug
because of a NullReferenceException
(see snapshots below) .
Here is my code:
Model:
public class ProductModel
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public bool Selected { get; set; }
public string[] CheckedColumn { get; set; }
}
View:
@model IEnumerable<DemoApp.Models.ViewModels.ProductModel>
@{
ViewBag.Title = "CheckView";
}
<table>
<tr>
<th>
ProductId
</th>
<th>
ProductName
</th>
<th>
Selected
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ProductId)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
@Html.CheckBoxFor(modelItem => item.Selected)
</td>
</tr>
}
</table>
@using (Html.BeginForm())
{
<div>
<input type="submit" name="AddResult" value="CheckView"/>
</div>
}
Controller:
[HttpGet]
public ActionResult CheckView()
{
DatabaseEntities db = new DatabaseEntities();
var prodList = from b in db.SysUser3
select new ProductModel
{
ProductId = b.ProductId,
ProductName = b.ProductName,
Selected = b.SelectedProducts
};
var p = prodList.ToList();
return View(p);
}
[HttpPost]
public ActionResult CheckView(FormCollection collection)
{
try
{
ProductModel model = new ProductModel();
// Get all the selected checkboxlist, do db insertion
model.CheckedColumn = collection["CheckView"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Here are some of the snapshots I took while running the project
Am I doing something wrong in my View or Controller? can someone please help me ?