我有一个静态类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>
由于
答案 0 :(得分:5)
您可以使用window.location.href
重定向到将调用此方法的应用程序上的控制器操作:
<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>
将重定向到以下控制器操作并将所选值传递给它:
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>