开发者

Populating an @Html.DropDownListFor() using a custom Method in MVC

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 mat开发者_如何转开发ter 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.


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")
)


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜