在mvc中维护DropdownList选择的值

时间:2014-07-23 08:57:38

标签: asp.net asp.net-mvc entity-framework razor

我有一个DropDown并且在selcted indexchanged上强制回发并绑定一个表,但是在回发之后它没有保持状态。

我的观点是

@Html.DropDownListFor(m=>m.fkSubMenuID, (IEnumerable<SelectListItem>)ViewBag.list,"Select" 

,new { id = "ddlSubMenu",onchange="SelectedIndexChanged()" })

我的控制器是

public ActionResult ChildMenuOfSubMenu()

    {
        if (Session["DDlId"] == null || Convert.ToInt32(Session["DDlId"]) == 0)
        {
            UlrikenEntities dc = new UlrikenEntities();
            var query = (from m in dc.ulriken_tblChildMenu
                         join sb in dc.ulriken_tblSubMenu on m.fkSubMenuID equals sb.pkSubMenuID
                         where m.Status == true && sb.fkMainMenuID == 1
                         select m).ToList();
            Ulriken.Models.ChildMenu ObjHomeEvents = new Models.ChildMenu();
            ObjHomeEvents.FormDetails = query;
            FillDeptName();
            Session["DDlId"] = null;
            return View(ObjHomeEvents);
        }
        else
        {
            Int64 id = Convert.ToInt64(Session["DDlId"]);
            UlrikenEntities dc = new UlrikenEntities();
            var query = (from m in dc.ulriken_tblChildMenu
                         join sb in dc.ulriken_tblSubMenu on m.fkSubMenuID equals sb.pkSubMenuID
                         where m.Status == true && m.fkSubMenuID == id && sb.fkMainMenuID==1
                         select m).ToList();
            Ulriken.Models.ChildMenu ObjHomeEvents = new Models.ChildMenu();
            ObjHomeEvents.FormDetails = query;
            FillDeptName();
            //string ddlValue= ViewData.TemplateInfo.GetFullHtmlFieldId("ddlSubMenu");

            Session["DDlId"] = null;
            return View(ObjHomeEvents);
        }


        //return View();
    }

我的javascript函数是:

   function SelectedIndexChanged() {        

        document.demoForm.submit();

  }

有人指导我在哪里做错了

1 个答案:

答案 0 :(得分:0)

您的控制器操作没有参数...控制器操作中至少需要一个参数来检索用户选择的值。

public ActionResult ChildMenuOfSubMenu(int fkSubMenuID) 
{
    // ....
}

当请求是HTTP GET时,有一个方法可以显示视图,而处理表单提交的另一个方法(HTTP POST)可能会更好:

public ActionResult ChildMenuOfSubMenu() 
{
    // This method gets called in a HTTP GET
}

[HttpPost]
public ActionResult ChildMenuOfSubMenu(int fkSubMenuID) 
{
    // This one gets called when user performs the submit to the form
}