MVC3剃须刀条件加载
我想实现以下内容: 一个combobox/DropDownListFor视图中的命名为“目标”。它包含(例如)A和B作为选择。 在同一视图中,我有另一个名为“中”的组合框。其内容取决于所选择的目标,例如: - 如果target =“A”,则组合框“medium”将显示1和2作为选项。 - 如果target =“B”,combobox“medium”将显示3和4作为选择。MVC3剃须刀条件加载
我已经成功实现了组合框“target”,但我不知道如何实现与“target”相关的combobox“medium”。如果我没有错,逻辑应该是:获取选定的目标标识符 - >找到与目标标识符相关的所有介质 - >填充组合框“介质”,结果。
这里是我当前视图(组合框 “目标”)的片段:
<div class="editor-label">
@Html.LabelFor(model => model.TargetId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.TargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.TargetId))
</div>
Thx提前。
你可以使用第一降的JavaScript的OnChange做一个AJAX调用获得选择A或B.
你从控制器得到您填写的下拉“JSON响应在此基础值在JS文件中”
做这样的事情:
$(document).ready(function() {
$("#target").change(function() { GetMediumValues("#target", "#medium"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMediumValues(objSource, objDest) {
var url = '/mySite/GetMediumValues/';
$.getJSON(url, { id: $(objSource).val() }, function (data) {
ClearDrop(objDest);
$.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
虽然在控制器
public ActionResult GetMediumValues(string id)
{
int myId = 0;
int.TryParse(id, out myId);
var select = new SelectList(repository.GetMediumValues(myId), "Id", "Name");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}
Thx。我仍然有2个问题。 Q1:在JS中var url是什么意思?我在localhost上运行我的webclient。所以我需要将URL设置为/ localhost/GetMediumValues /是否正确? Q2:我现在怎样才能实现combobox“中”? – MagB
Q1:网址来自映射网站的根目录。所以删除localhost。您也可以使用绝对网址,例如www.mysite.com/getvalues – Iridio
Q2:只需输出您的下拉列表中的空白选择列表。或者如果第一个下拉列表绑定了值,则已经填充。当你准备你的viewmodel imo时,你可以通过你的控制器来做到这一点 – Iridio
您将需要使用ajax来重新加载媒体组合框或JavaScript以动态更改值。 –