开发者

MVC3 Razor conditional loading

开发者 https://www.devze.com 2023-04-05 21:26 出处:网络
I want to implement following: A combobox/DropDownListFor named \"target\" in a view. It contains (e.g.) A and B as choice.

I want to implement following: A combobox/DropDownListFor named "target" in a view. It contains (e.g.) A and B as choice. In the same view I have another combobox named "medium". Its content depends on the chosen target, e.g.: - if target = "A", combobox "medium" will show 1 and 2 as choice. - if target = "B", combobox "medium" will show 3 and 4 as choice.

I have implemented combobox "target" successfully, but I don't know how to implement combobox "medium" related to "target". If I am not wrong, the logic should be: get the chosen targetid -> find all medium related to the targetid -> fill combobox "medium" with the result.

Here is snippet of my current view (combobox "target"):

开发者_JS百科
<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 in advance.


You could use the javascript OnChange of the first drop to do an ajax call to obtain the values based from the choice A or B.

Then with the JSon response you get from the controller you fill the dropdown "Medium"

in the JS file do something like this:

$(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>");
    });
});

}

While in the controller

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 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消