Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从数据库中获取数据并从列表中填充下拉列表<;对象>;在MVC中_C#_Asp.net_Linq_Asp.net Mvc 4_Html.dropdownlistfor - Fatal编程技术网

C# 从数据库中获取数据并从列表中填充下拉列表<;对象>;在MVC中

C# 从数据库中获取数据并从列表中填充下拉列表<;对象>;在MVC中,c#,asp.net,linq,asp.net-mvc-4,html.dropdownlistfor,C#,Asp.net,Linq,Asp.net Mvc 4,Html.dropdownlistfor,我有一个模型: public partial class UserRole { public int ID { get; set; } public int UserID { get; set; } public int RoleID { get; set; } public int Status { get; set; } public virtual user Users { get; set; } public virtual Role R

我有一个模型:

public partial class UserRole
{
    public int ID { get; set; }
    public int UserID { get; set; }
    public int RoleID { get; set; }
    public int Status { get; set; }

    public virtual user Users { get; set; }
    public virtual Role Roles { get; set; }
}

public partial class user
{
    public user()
    {
        Roles = new List<SelectListItem>();
    }

    public long id { get; set; }
    public string email { get; set; }
    public string password { get; set; }
    public System.DateTime reg_date { get; set; }
    public byte validated { get; set; }
    public virtual ICollection<UserRole> UserRoles { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }

    public IEnumerable<SelectListItem> Roles { get; set; }

    //public IEnumerable<Role> Roles { get; set; }
}

public partial class Role
{
    public int ID { get; set; }
    public string RoleName { get; set; }
    public string Desc { get; set; }
    public int Status { get; set; }
    public virtual ICollection<UserRole> UserRoles { get; set; }
}
公共部分类用户角色
{
公共int ID{get;set;}
public int UserID{get;set;}
public int RoleID{get;set;}
公共int状态{get;set;}
公共虚拟用户{get;set;}
公共虚拟角色{get;set;}
}
公共部分类用户
{
公共用户()
{
角色=新列表();
}
公共长id{get;set;}
公共字符串电子邮件{get;set;}
公共字符串密码{get;set;}
public System.DateTime注册表_date{get;set;}
已验证的公共字节{get;set;}
公共虚拟ICollection用户角色{get;set;}
public int RoleId{get;set;}
公共字符串RoleName{get;set;}
公共IEnumerable角色{get;set;}
//公共IEnumerable角色{get;set;}
}
公共部分类角色
{
公共int ID{get;set;}
公共字符串RoleName{get;set;}
公共字符串Desc{get;set;}
公共int状态{get;set;}
公共虚拟ICollection用户角色{get;set;}
}
要加载视图的控制器:

public ActionResult AssignRole(long id = 0)
    {
        user UserModel = new user();
        int UserId = Convert.ToInt32(id);
        IList<user> Users = new List<user>();
        var query = from Role in db.Roles
                    join UserRole in db.UserRoles on Role.ID equals UserRole.RoleID
                    join user in db.users on UserRole.UserID equals user.id
                    where UserRole.UserID == UserId
                    select new { RoleName  = Role.RoleName, email = user.email, UserId = user.id };



        var userss = query.ToList();
        foreach(var userList in userss)
        {
            Users.Add(new user()
                {
                    id = userList.UserId,
                    email = userList.email,
                    RoleName = userList.RoleName
                });
        }

        LoadRoles(Users);
        return View(Users);
    }

public void LoadRoles(IList<user> model)
    {

        var Roles = db.Roles.AsQueryable<Role>().Select(x => new SelectListItem()
        {

            Text = x.RoleName,
            Value = SqlFunctions.StringConvert((double) x.ID)
        }).ToList();

        var UserModel = new user()
        {
            Roles = Roles.ToList()
        };

    }
公共操作结果分配角色(长id=0)
{
user UserModel=新用户();
int UserId=Convert.ToInt32(id);
IList Users=新列表();
var query=来自db.Roles中的角色
在db.UserRoles中加入UserRole,在Role.ID上等于UserRole.RoleID
在数据库中加入用户。UserRole.UserID等于user.id上的用户
其中UserRole.UserID==UserID
选择新建{RoleName=Role.RoleName,email=user.email,UserId=user.id};
var userss=query.ToList();
foreach(userss中的var userList)
{
添加(新用户()
{
id=userList.UserId,
email=userList.email,
RoleName=userList.RoleName
});
}
加载角色(用户);
返回视图(用户);
}
公共void加载角色(IList模型)
{
var Roles=db.Roles.AsQueryable().Select(x=>newselectListItem()
{
Text=x.RoleName,
Value=SqlFunctions.StringConvert((双精度)x.ID)
}).ToList();
var UserModel=新用户()
{
Roles=Roles.ToList()
};
}
我可以在视图的第一部分从LINQ中获取其他值,但无法填充dropdownlist

<fieldset>
<div>
    <table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.RoleName)
            </th>
            <th></th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.email)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.RoleName)
                </td>
                <td>
                    @Html.ActionLink("Delete", "Delete", new { id = item.id })
                </td>
            </tr>
        }
    </table>
</div>

<div class="display-label">
    @Html.DisplayName("Add Role")
</div>

@foreach (var item in Model)
{
    <div class="display-field">
        @Html.DropDownListFor(modeIteml => item.RoleId, item.Roles)
    </div>
}

<p>
    <input type="submit" value="Assign" />
</p>

@DisplayNameFor(model=>model.email)
@DisplayNameFor(model=>model.RoleName)
@foreach(模型中的var项目)
{
@DisplayFor(modelItem=>item.email)
@DisplayFor(modelItem=>item.RoleName)
@ActionLink(“删除”,“删除”,新的{id=item.id})
}
@Html.DisplayName(“添加角色”)
@foreach(模型中的var项目)
{
@DropDownListFor(modeIteml=>item.RoleId,item.Roles)
}


如何填充dropdownlist?我已经试了很多次了,但还是没有成功。

如果你这样写,你会发现它更清晰:

public ActionResult AssignRole(int id = 0)
{
    var user = (from u in db.users
               join r in db.UserRoles on r.UserId equals u.id into g
               where u.id == id
               select new user
               {
                   id = u.id,
                   email = u.email,
 // assign the properties like any normal select.
                   Roles = g.Select(x => new Role { RoleName = x.rolename ... })
               })
               .FirstOrDefault();

    return View(user); // Update your view to expect a single user
}
通过这种方式,您可以在快速访问数据库的过程中获得所需的一切,并且您的模型代表了您所拥有的一切(一个具有多个角色的用户)

如果您想要一个单独的角色列表,我建议为该场景设置一个单独的视图模型。i、 e

public class AssignRolesModel 
{
    public user User { get; set; }
    public IEnumerable<Role> AvailableRoles { get; set; }
}

我认为LoadRoles方法存在问题,因为您已经通过了IList模型,但该方法中没有model.Roles分配。能否在cshtml文件中显示您的
@model
?可能是出了什么问题?是的,我从LoadRoles这里获取值,但无法将它们传递给主对象。有什么建议吗?@naeemlik您必须循环模型列表中的每个用户对象,并且必须设置Roles属性,因为您的Roles属性位于用户对象内。@Sandeep是正确的。现在我不在手机上,我将更新我的答案,以便更清楚地了解最佳做法。@Steve我在LINQ查询中遇到错误。它说,“R”的名称不在“相等”的左边,考虑交换“相等”的两边的表达式。我尝试过交换表达式,但似乎还不起作用。可能是因为“equals”运算符左侧的参数需要是对以前使用的表的引用。因为我只引用了用户n个角色,但我有UserRole表中未引用的UserID。。不知道如何在查询中修复它。另外,在您注释为“//分配属性”的角色中传递什么?谢谢如果您不需要他们当前拥有的用户角色,那么您可以删除加入和对角色的分配。否则,请改为加入用户角色
var viewModel = new AssignRolesModel
               {
                   User = user,
                   Roles = db.Roles
                             .Select(x => 
                                new SelectListItem()
                                {
                                    Text = x.RoleName,
                                    Value = SqlFunctions.StringConvert((double) x.ID)
                                })
                             .ToList()
               };

return View(viewModel);