Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Partial View needs a controller, but can I make this non-public?

Is it possible to create a Partial View, which has a controller, which can be called from another view using

Html.RenderAction(...)

BUT without that same controller being accessible via a URL?

So for example

public class ArticlesController : Controller
{
    public ActionResult HomeList()
    ...
}

Gives a list of latest articles for the bottom of my web pages.

So I call this from

_Layout.cshtml

However I dont want someone coming to

mysite.com/Articles/HomeList

and seeing the same list for various reasons (security, SEO, etc.)

Thanks

Edit:

I ended up using my own attribute class, thanks to Russ's help:

public class ChildActionOnly404Attribute : FilterAttribute, IAuthorizationFilter
{
    void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.IsChildAction)
        {
            throw new HttpException(404, "");
        }
    }
}
like image 352
Martin Capodici Avatar asked Jan 18 '23 20:01

Martin Capodici


1 Answers

apply the ChildActionOnlyAttribute to the action. This means that it

  1. can only be called from inside the application and not directly via route matching
  2. can be called only with the Action or RenderAction HTMLHelper extension methods

I've found it to be useful for cross-cutting concerns like menus and navigation.

like image 156
Russ Cam Avatar answered Feb 01 '23 00:02

Russ Cam