开发者

Prevent partial view from loading

开发者 https://www.devze.com 2023-01-28 19:45 出处:网络
How can i prevent a partial view from being loaded by typing http://m开发者_C百科ydomain.com/site/edit/1 Is there any way of doing this?

How can i prevent a partial view from being loaded by typing http://m开发者_C百科ydomain.com/site/edit/1 Is there any way of doing this?

/Martin


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消