我尝试让以下部件运行,但总是失败。目标是:如果选择了组合框中的目标,则mediaId的组合框应填充相应的值。此时我只是模仿mediaId组合框的值。谁能告诉我如何正确地组合它们? Thx提前。
视图Medium.cshtml:
<script src="@Url.Content("~/Scripts/PartialLoad.js")" type="text/javascript"></script>
<div class="editor-label">
@Html.LabelFor(model => model.Files[i].TargetId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Files[i].PTargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId))
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Files[i].MediaId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Files[i].MediaId, (ViewData["mediaIds"] as SelectList).MakeSelection(1))
</div>
javascript partialload.js
$(document).ready(function () {
$("#targets").change(function () { GetMValues("#targets", "#mediaIds"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMValues(objSource, objDest) {
var url = '/GetMValues/';
$.getJSON(url, { id: $(objSource).val() },
function (data) {
ClearDrop(objDest); $.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
homecontroller.cs
public ActionResult GetMValues(String id)
{
int myId = 0;
int.TryParse(id, out myId);
var mediumIds = new List<long>();
int max = myId + 3;
// just to emulate the data in the list
for ( long l = 1 ; l < max ; l++ ){
mediumIds.Add(l);
}
var select = new SelectList(mediumIds, "PTargetId", "TargetId");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}
答案 0 :(得分:0)
此处您正在使用下拉列表的ID选择器:$("#targets")
但您的下拉列表似乎没有此ID。也许你想为它分配一个id或一个类:
@Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { id = "targets" }
)
但是因为这似乎是重复的,你不能拥有多个具有相同id的元素,所以类选择器可能更合适:
@Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { @class = "targets" }
)
然后:
$(document).ready(function () {
$(".targets").change(function () {
...
});
});
#mediaIds
显然相同。