2

I am new to MVC4 and please bear with me. I am building a portal where users will be shown different widgets. Lets just say widgets are some rectangular boxes with a title and a content. What would be a better way to implement this? i am planning to use partial views. And then call Html.renderaction on the aggregate view. Is this a good choice or is there a better way to do it?

2.)Also when the widget encounters any exception i would like to show a custom error message just on the widget area. I dont want the entire page to be redirected to an error page. Just the rectangle area alone.

Hari Subramaniam
  • 1,814
  • 5
  • 26
  • 46

1 Answers1

1

@Html.RenderAction should do the work, for the exceptions a try/catch can help you:

[ChildActionOnly]
public ActionResult Widget(int id) {
    try
    {
      var widget = Repository.GetWidget(id);
      return PartialView(widget);
    }
    catch
    {
      return PartialView("WidgetErrorPage");
    }
}

UPDATE: In that case you can use an ActionFilter to handle the exceptions, like explained here Return View from ActionFilter or here Returning a view with it's model from an ActionFilterAttribute:

public class WidGetHandleException : ActionFilterAttribute
    {
        protected override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = new PartialViewResult
            {
                ViewName = "WidgetErrorPage",
                ViewData = filterContext.Controller.ViewData,
                TempData = filterContext.Controller.TempData,
            };
        }
    }

And then decorate all your widget actions like this:

 [ChildActionOnly]
 [WidGetHandleException]
 public ActionResult Widget() 
 {

 }
Community
  • 1
  • 1
JOBG
  • 4,544
  • 4
  • 26
  • 47
  • Thank you. Instead of doing in every action is there a centralized way to do that exception handling and redirecting? – Hari Subramaniam Feb 23 '13 at 11:53
  • I assume you will use just one Action to render all widgets based on an id, you can also set the custom errors like explained here http://stackoverflow.com/questions/553922/custom-asp-net-mvc-404-error-page but im not sure that will help you in this case, AFAIK that will render a full page error not a partial page. – JOBG Feb 24 '13 at 00:16
  • I have many widgets. My site is primarily composed of widgets only. So i will have a lot of action methods for those widgets – Hari Subramaniam Feb 24 '13 at 05:17
  • Updated answer with `ActionFilter` alternative – JOBG Feb 24 '13 at 20:38