I want to use partial views with AJAX calls in ASP.NET MVC, and this is the first time I'm using it. I just searched to see if there is anything special I should know beforehand, and one of'em that I'm curious about, is to see if there is any special attribute that should be set or is related to AJAX calls? Something like [ChildActionOnly]
or [HttpGet]
相关问题
- MVC-Routing,Why i can not ignore defaults,The matc
- Entity Framework throws exception - Network Relate
- Custom Attribute to Process info before a method i
- parameters in routing do not work MVC 3
- Slow loading first page - ASP.NET MVC
相关文章
- “Dynamic operations can only be performed in homog
- How to get a list of connected clients on SignalR
- How do you redirect to the calling page in ASP.NET
- Change color of bars depending on value in Highcha
- The program '[4432] iisexpress.exe' has ex
- ASP.Net MVC 4 Bundles
- How to get server path of physical path ?
- Cannot implicitly convert Web.Http.Results.JsonRes
A spinoff of Muhammad's answer letting you specify that it mustn't be an ajax request as well:
This lets you do things like...
There is an [AjaxOnly] attribute provided in the ASP.NET MVC 3 Futures collection. It's a part of the official ASP.NET MVC Codeplex site that provides features before they are officially included in a future version of ASP.NET MVC.
You can download it here. To use it, add a reference to the Microsoft.Web.Mvc assembly included in the release package.
There is an explanation of the attribute on this page, along with all the other great features you can use.
my solution follows the
[ChildActionOnly]
implementation:ASP.NET MVC provides an extension method to check if an Request is an Ajax Request. You can use it to decide if you want to return a partial view or json result instead of a normal view.
To limit an action method to Ajax calls only you can write a custom attribute. In case of a normal request this filter will return a 404 not found http exception.
you can use it like that:
I don't think there is built in attribute for ajax but its not too hard to create one. you can create AjaxOnly filter like
and decorate your action methods like
Look at this post for another way of implementing this attribute
For those looking for a .NET Core solution it's a little bit more involved, as
IsAjaxRequest()
is no longer available.Below is the code I've used in production on several projects to great effect.