我有2个带有jquery代码的单选按钮,可以使用他们选择的选项重建下拉列表。我有下面的代码,它转到正确的方法和构建选择列表的方法正常工作,并在方法完成后,下拉列表项根本不会更改。一切似乎都是正确的,但它不起作用。有没有人有任何想法?
查看
$('#singleSpacingRadio').change(function () {
var url = "/Home/NumberOfPagesList?id=" + $('#singleSpacingRadio').val();
$.getJSON(url, function (data) {
var items = "<option>--Test--</option>";
$.each(data, function (i, numberOfPages) {
items += "<option value='" + numberOfPages.Value + "'>" + numberOfPages.Text + "</option>";
});
$("#numberOfPagesList").html(items);
});
});
$('#doubleSpacingRadio').change(function () {
var url = "/Home/NumberOfPagesList?id=" + $('#doubleSpacingRadio').val();
$.getJSON(url, function (data) {
var items = "<option>--Test--</option>";
$.each(data, function (i, numberOfPages) {
items += "<option value='" + numberOfPages.Value + "'>" + numberOfPages.Text + "</option>";
});
$("#numberOfPagesList").html(items);
});
});
<div class="row">
@Html.LabelFor(model => model.Spacing, "Spacing:")
@Html.RadioButtonFor(model => model.Spacing, "Single", new { id = "singleSpacingRadio" }) Single
@Html.RadioButtonFor(model => model.Spacing, "Double", new { id = "doubleSpacingRadio" }) Double
</div>
控制器
public ActionResult NumberOfPagesList(string id)
{
var numberOfPagesList = from n in NumberOfPages.GetNumberOfPages()
where n.Spacing == id
select n;
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(numberOfPagesList.ToArray(), "numberOfPagesValue", "numberOfPagesName"), JsonRequestBehavior.AllowGet);
}
else
{
return RedirectToAction("Contact");
}
}
public class NumberOfPages
{
public string Name { get; set; }
public string Value { get; set; }
public string Spacing { get; set; }
public static IQueryable<NumberOfPages> GetNumberOfPages()
{
return new List<NumberOfPages>
{
new NumberOfPages
{
Name = "1 Page (Approx. 550 Words)",
Value = "1",
Spacing = "Single"
},
new NumberOfPages
{
Name = "1 Page (Approx. 275 Words)",
Value = "1",
Spacing = "Double"
},
new NumberOfPages
{
Name = "50 Pages (Approx. 13750 Words)",
Value = "50",
Spacing = "Double"
}
}.AsQueryable();
}
答案 0 :(得分:1)
将html更改为
@Html.RadioButtonFor(m => m.Spacing, "Single", new { @class = "spacing", id="single" })
<label for="single">Single</label>
@Html.RadioButtonFor(m => m.Spacing, "Double", new { @class = "spacing", id="double" })
<label for="double">Double</label>
和脚本
$('.spacing').click(function() {
var select = $("#numberOfPagesList");
select.empty().append($('<option></option>').val('').text('--Test--'));
var url = '@Url.Action("NumberOfPagesList", "Home")';
$.getJSON(url, { id: $(this).val() }, function (data) {
$.each(data, function (i, item) {
select.append($('<option></option>').val(item.Value).text(item.Name));
});
});
});
另请注意,您无需将收藏集转换为SelectList
,只需要以下内容
return Json(numberOfPagesList, JsonRequestBehavior.AllowGet);