I have a page where i am displaying image, id, name and address. I have added checkbox and multiple submit buttons to delete update or add new records.
But when I click on any submit buttons i am getting unhandled exception error. (for example I have selected a checkbox and clicked delete button my control is going to Mycontroller from view and to the delete switch case. It is deleting the record but again when it is coming back to view I am getting the NullReferenceException.)
View :
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post))
{
@if (Model.Count> 0) // .NullReferenceException
{
@foreach (var MyDB in Model)
{
<div class="col-md-2">
<img src="@Url.Content(photos.photo_url)" style="width:100px; height:100px;" />
</div>
Html.LabelFor(model => MyDB.ID, new
{
@class = "control-label col-md-2"
})
<div class="col-md-2">
@Html.EditorFor(model => MyDB.ID)
@Html.ValidationMessageFor(model => MyDB.ID)
</div>
@Html.LabelFor(model => MyDB.name, new
{
@class = "control-label col-md-2"
})
<div class="col-md-2">
@Html.EditorFor(model => MyDB.name)
@Html.ValidationMessageFor(model => MyDB.name)
</div>
@Html.LabelFor(model => MyDB.address, new
{
@class = "control-label col-md-2"
})
<div class="col-md-2">
@Html.EditorFor(model => MyDB.address)
@Html.ValidationMessageFor(model => MyDB.address)
</div>
<div class="col-md-1">
input type="checkbox" class="checkboxes" value="@MyDB.id" name="id" />
</div>
}
}
}
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="submitButton" value="UPDATE" />
<input type="submit" name="submitButton" value="ADD" />
<input type="submit" name="submitButton" value="DELETE" />
</div>
Controller :
public ActionResult MyController(IEnumerable<int> id, string submitButton)
{
switch (submitButton)
{
case "DELETE":
foreach (var item in id)
{
var delete = _db.MyDB.FirstOrDefault(s => s.id == item);
if (delete != null)
{
_db.MyDB.Remove(delete);
}
}
break;
case "ADD":
if (!ModelState.IsValid)
{
return RedirectToAction("ADDRecordPage", new
{
id
});
}
if (id == null)
{
return RedirectToAction("ADDRecordPage", new
{
id
});
}
break;
case "UPDATE" :
ViewBag.Message = "UPDATE";
break;
}
_db.SaveChanges();
ViewBag.Message = "Saved";
return View();
}