Prevent Partial view to access directly in MVC

About

Partial View 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 prevent access by just adding a one attribute above to that controller action method named as “[ChildActionOnly]”.
 
Please visit the article to know more about Partial View with sample application on my blog.

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. 
  1. public class DemoController : Controller    
  2. {    
  3.     /// <summary>    
  4.     /// Demo Partial Result    
  5.     /// </summary>    
  6.     /// <returns></returns>    
  7.     public ActionResult DemoPartialResult()    
  8.     {    
  9.         return PartialView("_Demo");    
  10.     }    
  11. }  
Now, you can create a partial view named as "_Demo.cshtml" with the template as "Empty (without model) " then add any sample text in that partial 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.
 
  1. /// <summary>    
  2. /// Demo Partial Result    
  3. /// </summary>    
  4. /// <returns></returns>    
  5. [ChildActionOnly]    
  6. public ActionResult DemoPartialResult()    
  7. {    
  8.     return PartialView("_Demo");    

 Now,If you are trying to access from the URL, It shows the error like the below.
 
 
Even, if you can't access the Partial View result action method from ajax call as well. For Example, In the ajax call in a javascript, you can write like the below. 
 
  1. <script type="text/javascript">    
  2.     $(document).ready(function () {    
  3.         $.ajax({    
  4.             type: "POST",    
  5.             traditional: true,    
  6.             url: '/Demo/DemoPartialResult',    
  7.             context: document.body,    
  8.             data: "",    
  9.             success: function (result) {    
  10.                 alert(result)    
  11.             },    
  12.             error: function (xhr) {    
  13.                 //debugger;    
  14.                 console.log(xhr.responseText);    
  15.             }    
  16.         });    
  17.     
  18.     });    
  19. </script>   
  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.
Ebook Download
View all
Learn
View all