gpt4 book ai didi

jquery - 在某些 .cs 文件中调用 Dropdownlistfor onchange 事件的方法

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

我有一个静态类 ItemInitializer,它有一个方法 CreateCookie()。我想每当下拉列表中的所选项目发生变化时调用此方法。我如何在 mvc 中做到这一点?

目前,我正在尝试这个

查看中:

    @Html.DropDownListFor(m => m.SelectedItem, Model.MyItemList, new { @id = "ddLForItems"})

在Controller中,方法是这样调用的,

       myModel.SelectedItem = ItemInitializer.CreateCookie();

现在,DropDownListFor 的 onchange 事件,需要再次调用 createCookie 方法。

使用jquery,如何调用CreateCookie方法。我有,

<script type = "text/javascript">
$(function () {
$("#ddLForItems").change(function () {
var item = $(this).val();
...?

//TBD:Create a cookie with value myModel.SelectedItem

});
});

</script>

谢谢

最佳答案

您可以使用 window.location.href 重定向到应用程序上将调用此方法的 Controller 操作:

<script type = "text/javascript">
$(function () {
$('#ddLForItems').change(function () {
var item = $(this).val();
var url = '@Url.Action("SomeAction", "SomeController")?value=' + encodeURIComponent(item);
window.location.href = url;
});
});
</script>

这将重定向到以下 Controller 操作并将所选值传递给它:

public ActionResult SomeAction(string value)
{
... you could call your method here
}

或者,如果您不想从当前页面重定向,您可以使用 AJAX 调用:

<script type = "text/javascript">
$(function () {
$('#ddLForItems').change(function () {
var item = $(this).val();
$.ajax({
url: '@Url.Action("SomeAction", "SomeController")',
type: 'POST',
data: { value: item },
success: function(result) {
// the controller action was successfully called
// and it returned some result that you could work with here
}
});
});
});
</script>

关于jquery - 在某些 .cs 文件中调用 Dropdownlistfor onchange 事件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556278/

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