在 MVC 中使用自定义方法填充 @Html.DropDownListFor()

发布于 2024-11-25 07:37:15 字数 953 浏览 5 评论 0原文

好吧,这是我的问题。我正在尝试使用我的角色减去 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

塔塔猫 2024-12-02 07:37:15

视图不应该负责从某些数据源中提取数据。它应该只负责操作控制器以vie模型的形式传递的数据。

您正在尝试做的是反 MVC 模式。您在此 GetUserRoles 方法中放入的代码是控制器(或数据访问层)的职责,其结果应该是您的视图模型的一部分。例如,您将拥有以下视图模型:

public class MyViewModel
{
    public string RoleName { get; set; }
    public IEnumerable<SelectListItem> UserRoles { get; set; }
}

然后您将拥有一个控制器操作,该操作将填充此视图模型:

public ActionResult Foo()
{
    // The GetUserRoles could also be part of a repository
    // that you would invoke here
    var userRoles = GetUserRoles();

    // Now construct the view model that you will pass to the view
    var model = new MyViewModel
    {
        UserRoles = userRoles.Select(x => new SelectListItem
        {
            Value = x,
            Text = x
        })
    };
    return View(model);
}

现在在您的视图中:

@model MyViewModel

@Html.DropDownListFor(
    m => m.RoleName, 
    new SelectList(Model.UserRoles, "Value", "Text")
)

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:

public class MyViewModel
{
    public string RoleName { get; set; }
    public IEnumerable<SelectListItem> UserRoles { get; set; }
}

and then you will have a controller action which will populate this view model:

public ActionResult Foo()
{
    // The GetUserRoles could also be part of a repository
    // that you would invoke here
    var userRoles = GetUserRoles();

    // Now construct the view model that you will pass to the view
    var model = new MyViewModel
    {
        UserRoles = userRoles.Select(x => new SelectListItem
        {
            Value = x,
            Text = x
        })
    };
    return View(model);
}

and now in your view:

@model MyViewModel

@Html.DropDownListFor(
    m => m.RoleName, 
    new SelectList(Model.UserRoles, "Value", "Text")
)
魄砕の薆 2024-12-02 07:37:15

除非您已将命名空间添加到 web.config 中,否则您可能需要完全限定方法 GetUserRoles() 才能正确注册。

Unless you have added your namespaces to your web.config, you may need to fully qualify the method GetUserRoles() for it to register correctly.

复古式 2024-12-02 07:37:15

我有类似的例子并且工作得很好
就我而言,我需要从 SQL 表的大列表中填充选定列表。

[在控制器中]

    public ActionResult GetDealTypes()
    {
        //Seleted Parameter
        return GetReferenceCodesByType("Deal");
    }


    private ActionResult GetReferenceCodesByType(string p_RefType)
    {
        IList<int> ArticleType = db.ReferenceTypes.Where(a => a.Code == p_RefType).Select(a => a.ID).ToList();

        var query = (from rt in db.ReferenceTypes
                     join rc in db.ReferenceCodeModels on rt.ID equals rc.ReferenceTypeId
                     where rt.Code == p_RefType
                     select new { rc.ID, rc.Description }).ToList();

        query.Insert(0, null);
        //Keeping in ViewBag - Which I ll access in view page
        ViewBag.DealTypes = query;
        return View();
    }

[在视图中]

@Html.DropDownListFor(g => g.DealTypeId, new SelectList(ViewBag.DealTypes, "Id", "Description"))

//ViewBag.DealTypes work as Data source which has been set in controller
@Html.ValidationMessageFor(model => model.DealTypeId)

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]

    public ActionResult GetDealTypes()
    {
        //Seleted Parameter
        return GetReferenceCodesByType("Deal");
    }


    private ActionResult GetReferenceCodesByType(string p_RefType)
    {
        IList<int> ArticleType = db.ReferenceTypes.Where(a => a.Code == p_RefType).Select(a => a.ID).ToList();

        var query = (from rt in db.ReferenceTypes
                     join rc in db.ReferenceCodeModels on rt.ID equals rc.ReferenceTypeId
                     where rt.Code == p_RefType
                     select new { rc.ID, rc.Description }).ToList();

        query.Insert(0, null);
        //Keeping in ViewBag - Which I ll access in view page
        ViewBag.DealTypes = query;
        return View();
    }

[In View ]

@Html.DropDownListFor(g => g.DealTypeId, new SelectList(ViewBag.DealTypes, "Id", "Description"))

//ViewBag.DealTypes work as Data source which has been set in controller
@Html.ValidationMessageFor(model => model.DealTypeId)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文