ajax和静态页面使用相同的partialView时的好习惯吗?

时间:2017-06-19 19:52:22

标签: ajax asp.net-mvc asp.net-core

当用户通过网址访问我的网站时,控制器会在其中生成_Layout + partialView

然后,当用户按站点行走时,控制器会生成相同的partialView并通过ajax发送。

这种情况有一个很好的解决方案吗?

P.S。:我的解决方法:

public class HomeController : Controller
{
    public ActionResult Index(int id, bool ajax = false)
    {
        var model = GetModelById(id);

        return ajax ? (ActionResult) PartialView(model) : View(model);
    }
}

/Home/Index/42 - 用于静态页面,/Home/Index/42?ajax=true用于ajax。

1 个答案:

答案 0 :(得分:1)

识别ajax请求:

var isAjax = Request.IsAjaxRequest()

Asp.Net Core中的替代方案:

var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";