【问题标题】:@Url.Action not working on AJAX call [duplicate]@Url.Action 不适用于 AJAX 调用 [重复]
【发布时间】:2018-02-11 22:26:49
【问题描述】:

我正在尝试使用 AJAX 将一组值从我的视图发布到我的控制器。但是,它并没有将 URL.Action 转换为相应的控制器和操作。而是在 URL 中显示为 url.action。

这是我的代码:

$('#addBtn').click(function() {
var patientId = $("#txtPatientId").val();

$.ajax({
    cache : false,
    url: '@Url.Action("AddPatient","Home")',
    type: 'POST',
    data: {patientId: patientId},
    }).done({});
});

控制器:

[HttpPost]
public ActionResult AddPatient(string patientId)
{

}

我在网络选项卡中看到的 URL 给我一个 404 错误,因为它试图访问 URL localhost/@Url.Action("AddPatient","Home")。

我错过了什么吗?

【问题讨论】:

  • 这表明您的脚本在外部文件中(剃刀代码未在外部文件中解析)
  • @StephenMuecke 所以唯一的解决方案是传递整个 URL?
  • 没有。但是您需要在主视图中创建它 - 比如<button id="addBtn" data-url="@Url.Action(...)" ... >,然后在您的脚本中读取它 (var url = $(this).data('url');)

标签: c# jquery ajax asp.net-mvc razor


【解决方案1】:

正如评论所说,您不能在cshtml文件之外使用剃须刀代码,即在外部js文件中

这里有两个选择

1 尝试静态网址

$.ajax({
    cache : false,
    url: '/Home/AddPatient'
    type: 'POST',
    data: {patientId: patientId},
    }).done({});
});

2 将 url 保存在 cshtml 文件中的全局变量中,然后在外部 js 文件中读取它 确保在全局变量被清除和初始化后引用文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多