I try to make following parts run, but always failed. The objective is: if a target in combobox is selected, the mediaId's combobox should be filled 开发者_如何学Cwith respective values. At this moment I just emulate the values of mediaId combobox. Can anyone show me how to combine them correctly? Thx in advance.
The view 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>
The 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>");
});
});
}
The 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
}
Here you are using an id selector for the dropdownlist: $("#targets")
but your dropdown doesn't seem to have such id. Maybe you want to assign it an id or a class:
@Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { id = "targets" }
)
But because this seems to be repeated and you cannot have multiple elements with the same id a class selector is probably more appropriate:
@Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { @class = "targets" }
)
and then:
$(document).ready(function () {
$(".targets").change(function () {
...
});
});
Same remark obviously for #mediaIds
.
精彩评论