1

I am a new in asp.net mvc 2.0, I tried to search about this article but still can not get the answer like what I want.

I have one form to assign the role to each employee. So I create one form that I can input the employee's name and select the role that they are in. The role are taking from table Role. I used linq to sql to query the RoleName and RoleID from table Role, and want to bind it to DropDownListFor in my view.

I have one model :

public class UserModels
{

   public string name { get; set; }
   public string role { get; set; }

}

This is what I did in my controller :

[HttpPost]
public ActionResult UserMaintenance(FormCollection frm)
{
if (ModelState.IsValid)
{
    EMP_DBSEntities context = new EMP_DBSEntities();
    tblUserLogin user = new tblUserLogin();
    user.UserName = frm["userLogin"].ToString();

    IEnumerable<SelectListItem> role_list = context.tblRoles.Select(d => new SelectListItem
    {
        Value = d.RoleID.ToString(),
        Text = d.RoleName
    });


    context.AddTotblUserLogins(user);
    context.SaveChanges();
    return View();
}
else
{
    return View();
}
}

Can anyone tell me how could I bind the role_list to my DropDownListFor<> in my view.

Thanks.

1 Answer 1

1

In order to create a drop down list you need a view model with 2 properties: a scalar property that will contain the selected value and a collection property that will contain the available options.

So as always in ASP.NET MVC start by writing a view model:

public class UserRoleViewModel
{
    [DisplayName("name")]
    public string EmployeeName { get; set; }

    [DisplayName("role")]
    public int? SelectedRoleId { get; set; }

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

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // fetch the roles
        // could come from a database or something
        var roles = new[] 
        { 
            new { RoleID = 1, RoleName = "Admin" }, 
            new { RoleID = 2, RoleName = "Foo" },
            new { RoleID = 3, RoleName = "Bar" },
            new { RoleID = 4, RoleName = "Baz" }, 
        };

        // Now we build the model
        var model = new UserRoleViewModel
        {
            EmployeeName = "John", // could come from a database or something
            SelectedRoleId = 1, // could come from a database or something
            Roles = new SelectList(roles, "RoleID", "RoleName")
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(UserRoleViewModel model)
    {
        return Content(
            string.Format(
                "Selected role for {0} is {1}", model.EmployeeName, model.SelectedRoleId
            )
        );
    }
}

and finally a view:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<UserRoleViewModel>" 
%>

...

<% using (Html.BeginForm()) { %>
    <%= Html.EditorFor(x => x.EmployeeName) %>
    <%= Html.DropDownListFor(x => x.SelectedRoleId, Model.Roles, "-- Role --") %>
    <button type="submit">OK</button>
<% } %>
Sign up to request clarification or add additional context in comments.

5 Comments

What error? What's the error message? It's weird because I didn't invent this code on the top of my head. It's something I copy-pasted from a fully working example that I have just setup. So I guess you must have changed something. What is it? What version of the framework are you using? I've noticed that you tagged your question with asp.net-mvc-2, so I have updated my view code because initially I posted a Razor sample. Now updated with a WebForms view engine sample.
This is my query var query = (from _role in context.tblRoles select _role).ToList(); and then I assign it foreach (var roleItem in query){ var role = new []{ new RoleID = roleItem.RoleID, RoleName = roleItem.RoleName} };} and then error No best type found for implicitly-typed array.
Why are you writing all this code (LINQ and loops and stuff)? Simply: Roles = new SelectList(context.tblRoles, "RoleID", "RoleName") directly when building the view model.
But I have one problem when I click submit, then it has an error Object reference not set to an instance of an object. in the line of <%= Html.DropDownListFor(x => x.SelectedRoleId, Model.Roles, "-- Role --") %>
I guess you haven't assigned your Roles property in the POST action, the same way you did in the GET action. Where do you think the DropDownList will take its items from? As you know only the selected value is sent to the server when you submit the form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.