您在这里有几种选择.
首先-用动词来区分您的请求,并有一个约定,例如所有GET接收html,而所有POST接收json.控制器将如下所示:
[HttpGet]
[ActionName("Index")]
public ActionResult IndexGet()
{
return View();
}
[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
return Json();
}
当然,使用正确的方法提出请求是客户端的事情.更新-动词仅在这里还不够-要保留一个动作名称,您还应该使用ActionName属性.感谢Joe Enos指出这一点.
第二-引入参数.假设默认情况下您正在发送html,但是如果ajax调用会附加一个参数isJson-给它json响应:
public ActionResult Index(bool? isJson)
{
if (isJson.HasValue && isJson.Value)
{
return Json();
}
return View();
}
第三-通过背后的机制区分请求.在您的情况下,似乎所有的ajax调用(只有它们)都应由json服务.然后,您可以使用Request.IsAjaxRequest()方法:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
return Json();
}
return View();
}
当然可以组合使用这些方法-例如,仅通过ajax将json响应发送给POST请求.