我从ASP.NET MVC Listbox handling selected item events
学到了例子我尝试了我的代码,就像这个例子一样,但我花了差不多3个小时来弄清楚为什么在从MVC 4 razor的列表中选择一个项目时没有触发事件。我不知道为什么我无法解决这个问题。请看我的代码我做错了什么。你的帮助意味着很多。
我需要触发事件并将值传递给Action参数(id)。
控制器:
[HttpGet]
public ActionResult Index()
{
viewModels.ViewCars = repository.GetCars();
var lstCars = new List<SelectListItem>();
foreach (Car car in viewModels.ViewCars)
{
var carItem = new SelectListItem()
{
Text = car.Description,
Value = car.Id.ToString(CultureInfo.InvariantCulture),
};
lstCars.Add(carItem);
}
viewModels.ListCarItems = lstCars;
return View(viewModels);
}
[HttpPost]
public ActionResult Index(int id)
{
List<CarData> data = repository.GetCarData();
CarData car = data.Single(m => m.Id == id);
viewModels.CarDetails = car;
return View(viewModels);
}
查看:
@model ConsoleMVC.Models.ViewModels
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.ListBox("carId", Model.ListCarItems)
使用Javascript:
<script type="text/javascript">
$(function() {
$('#carId').change(function () {
alert("PING!"); //Not fire event, why?
$.ajax({
type: 'POST',
url: '@Url.Action("Index","Home")',
data: JSON.stringify({ id: $('#carId').val()}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
window.location.href = data.Url;
}
});
});
});
</script>
更新
〜/查看/共享/ _Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<title>@ViewBag.Title - My ASP.NET MVC Application</title>
<meta name="viewport" content="width=device-width" />
<meta charset="utf-8" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="~/Content/screen.css" rel="stylesheet" />
<link href="~/Content/CarSite.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header class="header">
</header>
<div id="wrapper">
<div class="content">
<div id="body">
@RenderSection("featured", required: false)
<section style="padding: 20px;">
@RenderBody()
</section>
</div>
</div><!-- .content -->
<footer class="footer">
</footer><!-- .footer -->
</div>
</body>
答案 0 :(得分:0)
也许试试这个:
$(document).ready(function(){
$('#carId').change(function () {
alert("PING!");
...
});
});
答案 1 :(得分:0)
也许您的选择已动态添加到DOM,尝试在此处使用事件委派:
$(document).on('change', '#carId', function() {
// Your code here
});
如果没有,那么请确保您已正确包含jQuery,在加载jQuery
后添加jQuery代码,并且您的选择ID为carId
。