gpt4 book ai didi

jquery - 将下拉所选值作为操作方法传递

转载 作者:行者123 更新时间:2023-12-01 08:29:51 26 4
gpt4 key购买 nike

我有下拉选项programs2019、programs2020,当用户选择programs2019时,它将在 Controller 中调用操作方法programs2019。我尝试使用 jquery 并将 selectedvalue 传递给 @Url.Action() 但没有运气。我读过一篇文章,上面写着“@Url.Action 是服务器端代码,它在执行任何 JavaScript 代码之前执行。因此您不能在 @Url.Action() 调用中引用 JS 变量。”。那么如何将 selectedvalue 传递给调用操作呢?我的代码如下:

 <span id="Label1">Select a program year</span> &nbsp;


@Html.DropDownList("year", new List<SelectListItem>
{
new SelectListItem { Text = "2019", Value = "Programs2019"},
new SelectListItem { Text = "2020", Value = "Programs2020"}

}, "Select a year", htmlAttributes: new { style = "width: 300px;" })

和jquery:

<script  type="text/javascript">
$(document).ready(function () {

$("#year").change(function () {
var SelectedYr = $('#year').val();
$.ajax({
type: 'POST',
url: '@Url.Action(SelectedYr)',
dataType: 'json',
data: { year: SelectedYr },
success: function (result) {
}

});
});
});

Controller :

 public ActionResult Programs2019()
{
...
}
public ActionResult Programs2020()
{
...
}

最佳答案

我认为针对这个问题有几种解决方案。

以下是两种最简单的方法:

您可以在 ajax 上使用原始字符串而不是 @Url.Action,然后在其上使用一些棘手的 javascript 字符串连接。

$.ajax({
type: 'POST',
url: `/YourControllerName/Programs${SelectedYr}`,
success: function (result) {}
});

或者你也可以这样做

合并 Controller 上的操作并使用选定的年份来分离功能

Controller

public ActionResult ProgramSelect(int year)
{
if(year == 2019) {...}
...
}

Ajax

$.ajax({
type: 'POST',
url: '@Url.Action("ProgramSelect", "YourControllerName")',
data: { year: SelectedYr}
success: function (result) {}
});

关于jquery - 将下拉所选值作为操作方法传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61605570/

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