Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent partial view from loading

How can i prevent a partial view from being loaded by typing http://mydomain.com/site/edit/1 Is there any way of doing this?

/Martin

like image 853
Martin Overgaard Avatar asked Dec 05 '10 22:12

Martin Overgaard


People also ask

How do you prevent a partial view from being called directly from?

Just add the [ChildActionOnly] above your Action and should prevent user from accesing directly.

Can partial view have controller?

It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.

What is the difference between RenderPartial and partial?

The primary difference between the two methods is that Partial generates the HTML from the View and returns it to the View to be incorporated into the page. RenderPartial, on the other hand, doesn't return anything and, instead, adds its HTML directly to the Response object's output.

How do I load partial view?

To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.


2 Answers

If you load your partials through Ajax then you can check if the request HTTP header HTTP_X_REQUESTED_WITH is present and its value is equals to XMLHttpRequest.

When a request is made through the browser that header is not present

Here is a very simple implementation of an Action Filter attribute that does the job for you

public class CheckAjaxRequestAttribute : ActionFilterAttribute
{
    private const string AJAX_HEADER = "X-Requested-With";

    public override void OnActionExecuting( ActionExecutingContext filterContext ) {
        bool isAjaxRequest = filterContext.HttpContext.Request.Headers[AJAX_HEADER] != null;
        if ( !isAjaxRequest ) {
            filterContext.Result = new ViewResult { ViewName = "Unauthorized" };
        }
    }
}

You can use it to decorate any action where you want to check if the request is an ajax request

[HttpGet]
[CheckAjaxRequest]
public virtual ActionResult ListCustomers() {
}
like image 102
Lorenzo Avatar answered Oct 20 '22 02:10

Lorenzo


I believe the [ChildActionOnly] attribute is what you're looking for.

[ChildActionOnly]
public ActionResult Edit( int? id )
{
   var item = _service.GetItem(id ?? 0);
   return PartialView( new EditModel(item) )
}

Phil Haack has an article using it here

like image 35
TheRightChoyce Avatar answered Oct 20 '22 04:10

TheRightChoyce