Martin Overgaard
Martin Overgaard

Reputation: 355

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

Upvotes: 5

Views: 3698

Answers (2)

Lorenzo
Lorenzo

Reputation: 29427

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() {
}

Upvotes: 8

TheRightChoyce
TheRightChoyce

Reputation: 3084

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

Upvotes: 5

Related Questions