Given the following code how can I select a list item in my view to get the name via an id? I just want to get the name value from the list via a local @id variable that maps to the lists id range.
This really has nothing to do with dropdowns...perhaps selectlist is the wrong container for associative look up dictionaries?
-- Controller
ViewBag.TypeId = new SelectList(db.TypeIds, "TypeId", "Name");
-- View
@* ??? Get the name by a local @id *@
<div>ViewBag.TypeId.SelectItemNameById(@id)</div> @* Bad psuedo code here... *@
I will use Jquery with an ajax call on the onChange
of your dropdownlist.
$(document).ready(function () {
$("#MyDrop").change(function () { GetValue("#MyDrop"); });
});
function GetValue(objSource) {
var url = '/Home/Index/GetValue/';
$.getJSON(url, { id: $(objSource).val() }, function (data) {
//with data returned fill your fields
});
});
}
From the controller
public ActionResult GetValue(string id)
{
int intId = 0;
int.TryParse(id, out intId);
var myData = //Get the value from Id
return Json(myData, JsonRequestBehavior.AllowGet);
}
Remeber to use AllowGet
if you don't do a Post
call from your ajax (like in my example)
UPDATE to reflect the comments
To achive what you need use a Dictionary passed via ViewBag.
Then from your view you access the (Dictionary)ViewBag.MyDictionary.
Or whatever collection you prefer.