DropDownList保持为空

时间:2018-06-07 08:45:11

标签: c# asp.net-mvc visual-studio entity-framework

我搜索了很多内容并且我无法确定问题所在,它会返回一个空的DropDownList,其中包含" Seleccione Rol"文本,所以我想问题是DDL没有填充,我真的很感激任何帮助。

控制器:

public ActionResult Usuario_rol()
{
    using (proyectob_dbEntities db = new proyectob_dbEntities())
    {
        usuario_rol model = new usuario_rol();
        model.rolesList = db.roles;

        //roles model2 = new roles();
        //model.roles.rolesl = db.roles;
    }
    return View(new usuario_rol());           
}

观点:

<div class="form-group">
    @Html.LabelFor(model => model.roles, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-5">
        @Html.DropDownListFor(model => model.id_rol, new SelectList(Model.rolesList, "id", "rol"),"Seleccione Rol")
    </div>
</div>

型号:

public partial class usuario_rol
{
    public string id { get; set; }
    public string id_usuario { get; set; }
    public string id_rol { get; set; }
    public System.DateTime fecha_inicio_rel { get; set; }
    public System.DateTime fecha_termino_rel { get; set; }

    public virtual contactos contactos { get; set; }
    public virtual roles roles { get; set; }

    public virtual IEnumerable<roles> rolesList { get; set; }

    public usuario_rol()
    {
        rolesList = new List<roles>();
    }

数据库:

the DB looks like this

2 个答案:

答案 0 :(得分:2)

您没有发送模型进行查看,您正在传递新对象(空白)进行查看。

使用此return View(new usuario_rol());

更改return View(model);

答案 1 :(得分:0)

我认为这应该有效:

背景:

public class RoleContext  
{  
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYConnector"].ToString());  
    public IEnumerable<RoleTable> GetRoleList()  
    {  
        // it would be good if you put inline query in procedure
        string query = "SELECT RoleName,RoleId FROM RoleTable";  
        var result = con.Query<RoleTable>(query);  
        return result;  
   }  
}

ActionMethod:

public ActionResult Usuario_rol()
{
    RoleContext roleList = new RoleContext();
    usuario_rol model = new usuario_rol();
    using (proyectob_dbEntities db = new proyectob_dbEntities())
    {
        model.rolesList = new SelectList(roleList.GetRoleList(),"RoleName","RoleId");
    }
    return View(model);
}

观点:

@namespace of the model
<div class="form-group">
@Html.LabelFor(model => model.roles, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
    @Html.DropDownListFor(model => model.id_rol, model.rolesList ,"Seleccione Rol")
</div>