gpt4 book ai didi

JavaScript 未触发 Controller 中的方法

转载 作者:行者123 更新时间:2023-12-02 14:33:41 24 4
gpt4 key购买 nike

我正在尝试使用以下代码来触发 Controller 中的 Action 方法。

<script>
function updateSalary() {
var salary = $('#basicSalary').val();
var figure = $('#allowance').val();
$.ajax({
url: '@Url.Action("updateSalary","salary")',
type: "GET",
dataType: "JSON",
data: { salary: basicsalary, figure: allowance },
success: function (add) {
$('#basicSalary').val(salary)
}
})
}
</script>

Razor :

<td>
@Html.DropDownListFor(model => model.allowance, Model.allowances, "--please choose an option--", new { @class = "form-control", @onchange = "updateSalary()" })
</td>

Controller :

public ActionResult updateSalary (int salary, string figure)
{
if (figure == "Transport")
{
try
{
allowance trans = hc.allowances.First(x => x.name == figure);
if (trans != null)
salary = +Convert.ToInt32(trans.amount);
else
throw new excep("Record not found");
}
catch
{

}
}
return Json(salary,JsonRequestBehavior.AllowGet);
}

基本上,当用户选择allowance下拉列表时,allowance应该添加到网页上的basicSalary字段。我在 updateSalary Action 方法的起始大括号上放置了一个断点,以检查当我更改 allowance dropdownList 中的选择时 javaScript 是否在 Controller 中触发它。它没有射击。我不明白为什么。有人能看出为什么吗?

最佳答案

这里有一些错别字:

data: { salary: basicsalary, figure: allowance }

可能应该是:

data: { salary: salary, figure: figure }

给定您在 updateSalary javascript 函数开头声明的变量的名称。

为了跟踪此类问题,我建议您使用浏览器的开发人员工具栏。例如,如果您使用的是 Google Chrome,则可以单击 F12 来激活它,然后在 Console 选项卡中查找 JavaScript 错误。此外,在像您一样处理 AJAX 查询时,您可以查看“网络”选项卡,该选项卡将显示发送到服务器的所有请求以及相应的响应。这可以给您一个很好的指示问题可能出在哪里。

关于JavaScript 未触发 Controller 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com