Thursday, May 9, 2013

Show Errors in ASP.NET MVC


To show the errors i'm using the following approach and their might be other better solutions as well.

Create your error model.

public class ErrorViewModel
{
public string ErrorMessage { get; set; }
}

Catch the errors from your controller.
public ActionResult Delete(int id, FormCollection collection)
{


try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
string Message = "Can not Delete Stock ID: " + id;
return RedirectToAction("ShowError", new { Mes = Message });
}
}

 public ActionResult ShowError(string Mes)
{
ErrorViewModel errorModel = new ErrorViewModel() { ErrorMessage = Mes };
return View(errorModel);
}

View:
<h2 style="color: #FF0000">Error Occured!</h2>
<fieldset>
<div class="display-label">Error Message</div>
<div class="display-field"><%: Model.ErrorMessage %></div>
</fieldset>
<p>
<%: Html.ActionLink("Back to List", "Index") %>
</p>

No comments:
Write comments
Recommended Posts × +