我正在尝试运行此示例Rendering Partial Views using ajax,但我收到以下编译错误:
'的HttpRequest'不包含' IsAjaxRequest'的定义没有扩展方法' IsAjaxRequest'接受类型' HttpRequest'的第一个参数。可以找到。
public ActionResult ItemsList(string ID)
{
Item item = Service.GetItemById(ID);
if (Request.IsAjaxRequest())
{
return PartialView("viewPath", item);
}
else
{
return View("viewPath", item);
}
}
答案 0 :(得分:3)
检查用户代理,如下所示:
var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
答案 1 :(得分:1)
里卡多佩雷斯的答案适用于ajax请求,但错过了新的Fetch类型。这对我有用:
internal static class RequestHelpers
{
internal static bool IsAjaxRequest(this HttpRequest request)
{
return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
string.Equals(request.Headers["X-Requested-With"], "Fetch", StringComparison.Ordinal);
}
}