This
article will show you how you can pass or handle the controller error for
displaying in view of your mvc application. This application you can use in
mvc3, mvc4, mvc5, mvc6. How to handle error in controller action method
and pass error to the View?
So for this article first we will create a new mvc application and add a controller class file. In this article I have used viewbag to pass the error message to view.
So for this article first we will create a new mvc application and add a controller class file. In this article I have used viewbag to pass the error message to view.
So here is the
controller code.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace
MvcApplication1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult
Index()
{
ViewBag.Error = "This is example of
error.";
return View();
}
}
}
|
Here in
above code I have stored the error message in viewbag and then pass it to
display. Now create the view and add the below code into it.
@{
ViewBag.Title
= "Passing Controller Action Error
to View In MVC";
}
<h2>Index</h2>
@if (ViewBag.Error != null)
{
<h2> @ViewBag.Error</h2>
}
|
Here in
above code I have checked weather the error viewbag is having any value or not
if not then displaying the error message other wise it will not display the error
message. So here is the output.
0 comments:
Please let me know your view