Let's say I have a default project in MVC. I change the About link to be an Ajax form so that it only loads that part of the page. And of course I change the method to return PartialView('About') instead of View('About'). However, the problem arises when a user types in and goes to a link called localhost:port/Home/About. Now it loads about part but without the layout (without css, js, menu bars, etc.)! How can I prevent him from going into such page? Or maybe display an error page instead? Or even redirect him to go to View('About')? Options are endless, but how to know that the call was in a "wrong" way?
Asked
Active
Viewed 110 times
2
John Saunders
- 160,644
- 26
- 247
- 397
Andrius Naruševičius
- 8,348
- 7
- 49
- 78
-
Possible duplicate [how to know if the request is ajax in asp.net mvc?](http://stackoverflow.com/questions/3864179/how-to-know-if-the-request-is-ajax-in-asp-net-mvc) – Zabavsky Dec 16 '13 at 09:56
-
1Why do you care? If the user types in that link, then he deserves what he gets. – John Saunders Dec 17 '13 at 08:43
-
@JohnSaunders Interesting point of view! – Andrius Naruševičius Dec 17 '13 at 11:37
-
Consider: if the user doesn't like the result of entering that URL, then chances are he won't do that again. So why spend development time on something that won't happen very often and which won't have a detrimental effect in any case? – John Saunders Dec 17 '13 at 11:43
3 Answers
3
Add ChildActionOnly attribute to the controller method so MVC will not let user call it directly via http://localhost:port/Home/About
Alexey Raga
- 7,457
- 1
- 31
- 40
-
Very interesting! Sounds promising! Will definitely try that one when I'm back from work :) – Andrius Naruševičius Dec 16 '13 at 09:58
-
-
Nowhere. This URL will not be mapped to the controller action since it is marked with a `ChildActionOnly` attribute. However it would be possible to use `Html.Action(..)` helper to render the partial content, and it will work as this call is qualified as a child of another action that is being executed. – Alexey Raga Dec 16 '13 at 11:27
2
You can check in your action method if a request is ajax or not with
Request.IsAjaxRequest()
and take whatever action you need based on this.
This checks if the X-Requested-With header has been set to XMLHttpRequest by the calling client.
Detecting IsAjaxRequest() with ASP.NET MVC and JQuery Form Plugin / File Upload
0
as @Zabavsky it is seems like a duplicate...
another (very simple) solution may be to just seprate the methods. you anyway have seperate views. so the ajax call will trigger AboutAjax() and render the partialView and About() stays as is.
Shlo
- 1,036
- 2
- 10
- 23