Menu

Saturday 20 September 2014

Prevent Partial view to access directly in MVC


About:


As I discussed in earlier blog post, PartialView is mostly used as a type of user control. So, The partial view result should be used in other pages like a child Request and it should not be accessible by direct Route Url.

By Default, PartialViewResult controller will be accessible through Route Url. But, you can restrict or prvent access by just adding a one attribute above to that controller action method named as “[ChildActionOnly]”.

Example:


Now, you can check it out by the example, Just add the below lines of code in the controller action method in sample MVC application.

    public class DemoController : Controller
    {
        /// 
        /// Demo Partial Result
        /// 
        /// 
        public ActionResult DemoPartialResult()
        {
            return PartialView("_Demo");
        }
    }


Now, you create a partial view named as "_Demo.cshtml" with the template as "Empty (without model) " than add any sample text in that parital view.

Now, If you run the application it would accessible like the below.



But, If you add the attribute named as “[ChildActionOnly]” then it does not allow us to access directly from the URL. The code block looks like the below.
        /// 
        /// Demo Partial Result
        /// 
        /// 
        [ChildActionOnly]
        public ActionResult DemoPartialResult()
        {
            return PartialView("_Demo");
        }


Now,If you are trying to access from the URL, It shows the error like the below.


Event, if you can't access the Partial View result action method from ajax call as well.
For Example, The ajax call, you defined in the code like the below.

Now, If you are trying to access that page then you can identify the error in Console window of the browser is as follows.



Conclusion


I hope you got idea how to prevent Partial view Results directly accessing from URL or ajax calls in MVC. Please provide you valuable suggestions and comments if any.


3 comments:

  1. I want to access partial view only with AJAX call

    ReplyDelete
  2. Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. https://accesscontrolsystemsingapore.wordpress.com/2022/01/21/advantages-of-having-an-access-control-system-in-your-workplace/

    ReplyDelete