Wednesday, October 12, 2011

RAZOR cascading DropDownList

RAZOR


@Html.DropDownList("ddlElementCode",
TempData["ElementSelects"] as SelectList,
new { onchange = "populateValueTexts(this)" })




// Where the parameter “dropdown” is the first of the two

function populateValueTexts(dropdown) {
var myindex = dropdown.selectedIndex;
var selValue = dropdown.options[myindex].value
var xReq = jQuery.getJSON("ElementTexts",
{ elementCode: selValue },
null)
.complete(receiveValueTexts);
}

function receiveValueTexts(context, textStatus) {
var data = jQuery.parseJSON(context.responseText);

document.getElementById("ddlValueText").options.length = data.length;

jQuery.each(data, function (i, item) {
document.getElementById("ddlValueText").options[i].text = item.Text;
});
}

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ElementTexts(string elementCode)
{
Data d = new Data();

IList codes =
d.GetElementsByCode(Convert.ToInt32(elementCode));

SelectList items =
new SelectList((from c in codes select c.ELEMENT_VALUE_TXT).Distinct());

return Json(items, JsonRequestBehavior.AllowGet);
}

No comments: