我想將所有控制器和動作及其相應的角色存儲在數據庫中。因此,我創建了具有級聯DropDown列表的視圖,其中在下拉列表中選擇相應的控制器時,所有操作都將填充到操作的下拉列表中。我有以下代碼: 控制器:在asp.net mvc 3和剃刀視圖中控制器和動作的級聯下拉列表
public ActionResult Create()
{
var asm = Assembly.GetExecutingAssembly();
var controllerTypes = from d in asm.GetExportedTypes() where typeof(IController).IsAssignableFrom(d) select d;
List<SelectListItem> controllerdrop = new List<SelectListItem>();
foreach (var item in controllerTypes)
{
string cName = item.Name.ToString();
controllerdrop.Add(new SelectListItem() { Value = cName, Text = cName });
}
ViewBag.controller = controllerdrop;
ViewBag.role = ivr.get_all_role();
return View();
}
public ActionResult get_all_action(string ob)
{
Type t = Type.GetType(ob);
MethodInfo[] mi = t.GetMethods();
List<SelectListItem> action = new List<SelectListItem>();
foreach (MethodInfo m in mi)
{
if (m.IsPublic)
if (typeof(ActionResult).IsAssignableFrom(m.ReturnParameter.ParameterType))
{
action.Add(new SelectListItem() { Value = m.Name, Text = m.Name });
}
}
var List = new SelectList(action, "Value", "Text");
return Json(List, JsonRequestBehavior.AllowGet);
}
查看:
<script src="@Url.Content("~/Scripts/jquery-1.7.2.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#drop1").change(function() {
var id = $(this).val();
$.getJSON("/AssignRole/get_all_action/" + id,
function (data) {
var select = $("#drop2");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a action"
}));
$.each(data, function (index, data) {
select.append($('<option/>', {
value: data.Value,
text: data.Text
}));
});
});
});
});
</script>
@using (Html.BeginForm())
{
@Html.DropDownList("Controller", ViewBag.controller as SelectList, "Select a Controller", new { id = "drop1" })
<select id="drop2">
</select>
foreach (var list in ViewBag.role)
{
<input type="checkbox" name="role" [email protected] /> @list.Name
}
<input type="submit" value="Save" />
}
問題:
唯一的例外是在Type t = Type.GetType(ob);
這是因爲肥胖是null.how你的控制器配置的路由? –
我在的global.asax.cs如'routes.MapRoute( 「AssignRole」, 「AssignRole/get_all_action/{controllername}」, 新 { 控制器= 「AssignRole」, 行動= 「get_all_action」 配置, controllername = UrlParameter.Optional });' – CodeManiac
CodeManiac請看看這個:http://stackoverflow.com/faq#howtoask –