I use MVC 3, I have a View to Delete an element in my DB. A Service Layer check that all the logic is in place before authorizing the operation. In case of a Role violation a Message appear in the Html.Summary so the delete operation is abort.
My problem is when the message in the Html.Summary from the Service Layer arrive the View lost the data for the various fields, so you cannot see the ID, Name and Description for the item.
Could you point me out in the right direction? What I’m doing wrong? Thanks
public ActionResult Delete(int id)
{
Typology typology = _typologytService.FindById(id);
TypologyDeleteViewModel deleteViewModel = Mapper.Map<Typology, TypologyDeleteViewModel>(typology);
return View(deleteViewModel);
}
//
// POST: /ManageTypologies/Delete/5
[HttpPost]
public ActionResult Delete(TypologyDeleteViewModel deleteViewModel)
{
if (ModelState.IsValid)
{
Typology typology = Mapper.Map<TypologyDeleteViewModel, Typology>(deleteViewModel);
_typologytService.Delete(typology.TypologyId);
if (ModelState.IsValid)
return RedirectToAction("Index");
}
return View();
}
@model xxx.ViewModels.TypologyDeleteViewModel
@{
ViewBag.Title = "Delete";
}
<h2>
Delete</h2>
<h3>
Are you sure you want to delete this?</h3>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.TypologyId)
<fieldset>
<legend>TypologyDeleteViewModel</legend>
<div class="display-label">
TypologyId</div>
<div class="display-field">
@Html.DisplayFor(model => model.TypologyId)
</div>
<div class="display-label">
Name</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
<div class="display-label">
Description</div>
<div class="display-field">
@Html.DisplayFor(model => model.Description)
</div>
<p>
<input type="submit" value="Delete" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Change your post method to:
You are not passing the model back to the view when you return an invalid model state. Also, is there a reason that you check the ModelState.IsValid property twice in the above code? I am not seeing where you might be adding a ModelStateError and there is no path out of the second if statement.
Lastly, if your deleteViewModel contains any dropdown lists, etc (which in this case you do not appear to)…you will need to repopulate them before returning the view.
EDIT
In your case, the above would not work since you are not using EditorFor HTML helper for your other properties. Your view is spitting out the equivalent of
<span>tags for description, etc which are not posted back to the server. The only thing coming back is your Id property because it is in a<input type="hidden"field.So – in your case, you would need to update your action method to:
or, store your values in hidden input fields like you are doing with your ID so that all values are posted back to the server and you do not have to make a database call again.