在MVC中绑定下拉列表 [英] Bind Dropdown in MVC

查看:71
本文介绍了在MVC中绑定下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用实体框架绑定MVc 4中的下拉列表..



以及如何在视图中添加dropDown,即在CSHTML文件中。

解决方案

hi

 view 

@ Html.DropDownListFor(model => model.RoleId,(IEnumerable < SelectListItem > )MvcApplicationIntranetApplication.Helpres。 GenricHelpers.GetRolesList(), - 选择角色 - ,新{@class =required})







助手类代码: -

  public   static  SelectList GetRolesList()
{
try
{
using (TestDBEntities db = new TestDBEntities())
{
列表<角色> roleList =( from roles in db.Roles
// 其中,maritalStatus.Id == MaritalStatusId
选择角色)。 ToList<作用>();
// roleList.Insert(0,(new Roles {RoleId = 0,RoleName =}) );

return new SelectList(roleList, Id ROLENAME);
}
}
catch (SqlException)
{
return null ;
}
catch (EntityException)
{
return null ;
}
}







PLease标记如果它适合你


 @ Html.DropDownListFor(x = >  x.Group,(IEnumerable< SelectListItem>) ViewBag.SearchGroup)


how to bind dropdown in MVc 4 using Entity Framework..

and Also How dropDown is added in view i.e. in CSHTML file.

解决方案

hi

view

       @Html.DropDownListFor(model => model.RoleId, (IEnumerable<SelectListItem>)MvcApplicationIntranetApplication.Helpres.GenricHelpers.GetRolesList(), "--Select Roles --", new { @class = "required" })




helper class code:-

public static SelectList GetRolesList()
        {
            try
            {
                using (TestDBEntities db = new TestDBEntities())
                {
                    List<Role> roleList = (from roles in db.Roles
                                           //where maritalStatus.Id == MaritalStatusId
                                           select roles).ToList<Role>();
                    //roleList.Insert(0, (new Roles { RoleId = 0, RoleName = "" }));

                    return new SelectList(roleList, "Id", "RoleName");
                }
            }
            catch (SqlException)
            {
                return null;
            }
            catch (EntityException)
            {
                return null;
            }
        }




PLease mark if it work for you


@Html.DropDownListFor(x => x.Group, (IEnumerable<SelectListItem>)ViewBag.SearchGroup)


这篇关于在MVC中绑定下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆