You can test if the action has been called with AJAX then return JSON data and if not return a normal view:
public ActionResult Index()
{
var model = FetchModel();
if (Request.IsAjaxRequest())
{
return Json(model, JsonRequestBehavior.AllowGet);
}
return View(model);
}
Of course this if makes your controller action ugly. It would be far better to use action filters to avoid repeating this logic in multiple actions:
public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewResult = filterContext.Result as ViewResultBase;
if (viewResult != null)
{
if (viewResult.Model != null)
{
filterContext.Result = new JsonResult
{
Data = viewResult.Model,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
}
}
And then decorate your controller with this attribute:
[MyFilter]
public ActionResult Index()
{
var model = FetchModel();
return View(model);
}