You have several options here.
First - differentiate your requests by their verbs, and have a convention, such as all GET
s receive html, while all POST
s 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.