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.
- public class DemoController : Controller
- {
- /// <summary>
- /// Demo Partial Result
- /// </summary>
- /// <returns></returns>
- 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.
- /// <summary>
- /// Demo Partial Result
- /// </summary>
- /// <returns></returns>
- [ChildActionOnly]
- public ActionResult DemoPartialResult()
- {
- return PartialView("_Demo");
- }
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) {
- //debugger;
- console.log(xhr.responseText);
- }
- });
- });
- </script>
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.
Source collected from CSharpcorner.com
http://www.c-sharpcorner.com/Blogs/46605/prevent-partial-view-to-access-directly-in-mvc.aspx
No comments :
Post a Comment