Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is the correct way to have my Index() method return content based on the incoming accept/content-type headers.

I currently have an application I am trying to refactor that has an Index() method and a JsonData() method. The browser pulls this "index" page and then via Ajax requests the /jsondata URL. I would like to put both under Index() and change the response types depending on the incoming request. What is the correct way to do this under MVC 4?

Note: we are not using Web API.

share|improve this question

2 Answers

You have several options here.

First - differentiate your requests by their verbs, and have a convention, such as all GETs receive html, while all POSTs receive json. Controller will look like this:

[HttpGet]
public ActionResult Index()
{
    return View();
}


[HttpPost]
public ActionResult Index()
{
    return Json();
}

And of course its a client-side matter to make a request with correct method.

Second - introduce a parameter. Say by default you are sending html, but if ajax call appends a parameter isJson - give it json response:

public ActionResult Index(bool? isJson)
{
    if (isJson.HasValue && isJson.Value)
    {
        return Json();
    }

    return View();
}

Third - differentiate request by the mechanism behind them. In your case it seems that all ajax calls, and only them, should be served by json. Then you can use Request.IsAjaxRequest() method:

public ActionResult Index()
{
    if (Request.IsAjaxRequest())
    {
        return Json();
    }

    return View();
}

And of course it is possible to combine these methods - say send json response only to POST requests by ajax.

share

May try to resolve this with request AcceptTypes?

 public ActionResult Index()
        {
            if (Request.AcceptTypes.Contains("application/json"))
            {
                //
            }
            else 
            {

            }
            return View();
        }
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.