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]”.
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
- {
-
-
-
-
- public ActionResult DemoPartialResult()
- {
- return PartialView("_Demo");
- }
- }
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.
-
-
-
-
- [ChildActionOnly]
- public ActionResult DemoPartialResult()
- {
- 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.
- <script type="text/javascript">
- $(document).ready(function () {
- $.ajax({
- type: "POST",
- traditional: true,
- url: '/Demo/DemoPartialResult',
- context: document.body,
- data: "",
- success: function (result) {
- alert(result)
- },
- error: function (xhr) {
-
- console.log(xhr.responseText);
- }
- });
-
- });
- </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.