How can I distinguish between requests made from RenderAction and via AJAX? - asp.net-mvc

In ASP.NET MVC, there is a useful method Request.IsAjaxRequest that I can use to determine whether the request is made via AJAX. However, RenderAction method seems to be calling the controller/action via AJAX as well.
I would like the calls via RenderAction to return a View, whereas calls via AJAX to return a Json object. Is there any way I can distinguish calls from those two sources?
EDIT:
Re. jim: I simply call a RenderAction within a View:
In SomeView.ascx:
Html.RenderAction("Action", "AnotherController", new { id = "some ID" });

I believe you could use ControllerContext.IsChildAction to determine if a method was called by RenderAction().

Related

Pass javascript parameter to partial view in asp.net mvc

lets say I want to a partial view like the following sample
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
in the jsparameter I want to pass as a parameter that is the result of a javascript function. Maybe this is not logical because javascript runs on the client, but how can I achieve a similar functionality ? thank you in advance
If you need to call a part of a page based on some actions or values determined by actions on the client side, then you should think to use JavaScript (preferably jQuery) and Ajax.
Through jQuery-Ajax, you could easily call a Partial view through the Contoler and since it's a regular HTTP request, you would be able to pass all the parameters you need.
Using code as :
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
is not possible since it is rendered by the server before it's sent to the client browser.

Callinf action in controller via jquery

I am new to MVC and I am continuing to learn more each day. I am converting and webform application to MVC for practice and wanted to know is there a way to call GET on a action and return json, array or whatever I want on document.ready function? I can do this using webapi, but I would rather do it using an action in the controller. I like the helpers that they Microsoft provides but they are for forms and action links, etc. Thanks for any help.
$(document).ready(function(){
$.ajax(Somehow call controller action here with data), success(function that returns json data)
});
I think this article has a great explanation with examples
http://www.codeproject.com/Articles/41828/JQuery-AJAX-with-ASP-NET-MVC

How to call a function *only once* in ASP.NET MVC page cycle

I have an ASP.NET MVC web app and have a function that I need to call when the page loads only once. Right now I have the function being called from a base controller OnActionExecuted.
The issue I'm having is that this function is called multiple times - once for the page, and then multiple times for different ajax calls that I have on the page. I've tried putting the function on Controller Initialize but this is also called for each ajax call to a controller action. So is there some function in the ASP.NET MVC page cycle that only gets called when a page is requested (GET) and not for all of the ajax calls (POST)? The only thing I can think of is putting all of the ajax calls in separate controllers that don't inherit from the base controller but there must be a nicer solution.
Depending on how you're doing your AjaxRequests you could use something like the following:
public ActionResult Index()
{
if (!Request.IsAjaxRequest())
{
LoadConfiguration();
}
// Rest of Action method (snip)...
}
This works if, for instance, you're performing Ajax with the jQuery JavaScript library which sends a special token to the server to indicate that it's an Ajax call (I'm sure other libraries do this). This might be better just in case someone changes the JavaScript code to perform GET Ajax requests.
One thing you mentioned does intrigue me though "The issue I'm having is that this function is called multiple times" - actually 'technically' this is not true. It IS only getting called once....per request, all those Ajax calls are treated as separate requests by the server, as if the user is requesting a page via the web browser. It sounds like what you really need is a way to differentiate between web page HTTP Requests, and Ajax HTTP Requests, hence the above solution.
It came to me right after posting the question...
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
if (Request.HttpMethod == "GET")
{
LoadConfiguration();
}
}
You can either do this work in the application scope (on start, in global.asax or other similar approaches), or store a configuration object in the session (or a flag to identify it has already been done, if there is nothing to store).

How to simiulate a JSON call from an HTTP GET Call?

At this moment I am calling my index view in one of two ways. Using the normal http view and serializing it JSON. In order to test it I am using the code below, and it works. I want to get it with a http get call. Like (http://localhost/article,json or something similar. Any ideas.
$.getJSON("/Article", function(json) {
$.each(json, function(i, article) {
alert(article.title);
});
});
At this moment the index called to /article is being differentiated with the following IsAjaxRequest method. but my real question is if I am able to get around the .getJSON method in JQuery to test the following code.
if (Request.IsAjaxRequest()) {
return Json(articles);
} else {
return View(articles);
}
If you are trying to reuse the same action method for both a full GET (the page load) and an AJAX call (via getJSON), you'll run into issues because each action method should have a unique name. Otherwise, the MVC engine can't tell which action method should be called when a particular Url is requested.
You'll need two separate actions: one for the full page load that returns a ViewResult and the other for the AJAX call that returns a JsonResult. If you need the Urls for these actions to look the same, you can also play around with mapped routes that direct to different action methods.
So, how about:
/Article/Index
Maps to the default Index action (full page load)
/Article/Refresh
Maps to the Refresh action (asynchronous JSON call)
I'm not sure I understand the question correctly, but can't you make an optional parameter called "format", so that you pass in ?format=json to switch what reply type you get back?
if(Request.IsAjaxRequest() || (!string.IsNullOrEmpty(format) && format.Equals("json"))
{
...
}
If you're wondering how to test your action and you're talking about doing automated testing, see if this post answers your question.

Would you ever want an action method to not return an ActionResult?

In ASP.NET MVC the convention is that a controller action method should return an ActionResult (or a type derived from ActionResult).
However, you can write a public method that returns pretty much anything and if that method is called (from a browser) the framework will package the return value up as a ContentResult and the browser receives a page of plain text.
This is all very interesting - but would you ever want to do this?
When you want to render something directly from your controller? e.g. using Response.Write(...); (or using other Response methods).
Not returning anything from an action method is essentially not responding to the client's HTTP request with a response.
An empty request might make sense in some cases (HTTP status being enough of a reply), but all web application patterns return something more than this (including, if I understand it correctly, REST: the new state of the entity).

Resources