在 MVC 中使用自定义方法填充 @Html.DropDownListFor()
好吧,这是我的问题。我正在尝试使用我的角色减去 Admin
角色来填充 @Html.DropDownListFor()
。这工作得很好,但它显示了所有角色:
@Html.DropDownListFor(m => m.RoleName, new SelectList(Roles.GetAllRoles()))
但是,这显示了所有角色,包括 Admin
角色。
因此,我使用此方法创建了另一个类 UserHelper.cs
,该方法与 Roles.GetAllRoles()
基本相同:
public string[] GetUserRoles()
{
string[] userroles = null;
using (MainVeinDataDataContext conn = new MainVeinDataDataContext())
{
userroles = (from r in conn.Roles
where r.Rolename != "Admin"
select r.Rolename).ToArray();
}
return userroles;
}
但是,对于 MVC 非常陌生,我没有想法如何将此方法公开给视图中的 DropDownList。因此,无论我尝试什么,这都不起作用:
@Html.DropDownListFor(m => m.RoleName, new SelectList(GetUserRoles()))
我不确定我错过了什么,这让我发疯。希望有人知道我错过了什么。
Ok so here is my problem. I'm trying to populate an @Html.DropDownListFor()
with my Roles minus the Admin
Role. This works just fine, but it shows all roles:
@Html.DropDownListFor(m => m.RoleName, new SelectList(Roles.GetAllRoles()))
However this shows all roles including the Admin
roll.
So I have created another class UserHelper.cs
with this Method that is basicly the same thing as Roles.GetAllRoles()
:
public string[] GetUserRoles()
{
string[] userroles = null;
using (MainVeinDataDataContext conn = new MainVeinDataDataContext())
{
userroles = (from r in conn.Roles
where r.Rolename != "Admin"
select r.Rolename).ToArray();
}
return userroles;
}
However, being very new to MVC, I have no idea how to expose this Method to the DropDownList in the view. So this doesn't work no matter what I try:
@Html.DropDownListFor(m => m.RoleName, new SelectList(GetUserRoles()))
I'm not sure what I am missing and it is driving me crazy. Hopefully someone out there knows what I'm missing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
视图不应该负责从某些数据源中提取数据。它应该只负责操作控制器以vie模型的形式传递的数据。
您正在尝试做的是反 MVC 模式。您在此
GetUserRoles
方法中放入的代码是控制器(或数据访问层)的职责,其结果应该是您的视图模型的一部分。例如,您将拥有以下视图模型:然后您将拥有一个控制器操作,该操作将填充此视图模型:
现在在您的视图中:
A view should not be responsible for pulling data from some datasources. It should only be responsible for manipulating the data that it was passed by the controller under the form of a vie model.
What you are trying to do is an anti-MVC pattern. The code that you have put in this
GetUserRoles
method is the controller (or a data access layer) responsibility and the result of it it should be part of your view model. So for example you would have the following view model:and then you will have a controller action which will populate this view model:
and now in your view:
除非您已将命名空间添加到
web.config
中,否则您可能需要完全限定方法GetUserRoles()
才能正确注册。Unless you have added your namespaces to your
web.config
, you may need to fully qualify the methodGetUserRoles()
for it to register correctly.我有类似的例子并且工作得很好
就我而言,我需要从 SQL 表的大列表中填充选定列表。
[在控制器中]
[在视图中]
I have similer example and working nicely
In my case I need to populate Selected list from a big list of SQL Table.
[In controller]
[In View ]