views:

151

answers:

3

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);
            }
+1  A: 

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)

David Andres
A: 

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"))
{
    ...
}
Runeborg
A: 

If you're wondering how to test your action and you're talking about doing automated testing, see if this post answers your question.

andymeadows