SoftwareNerd
SoftwareNerd

Reputation: 1905

How to bind a column to DropDownList and get the value Selected in MVC3?

Hi Guys i have two tables which look like this

          usertable                                 RoleTable
   -----------------------                     ---------------------------
  UserID|UserName|Pwd|RoleID                        RoleID|RoleName
    1   |Anil    |123|1                               1   |Admin

now i am showing the usertable in a table,where he has an AddNew Link ,when the admin clicks on AddNew link i will show him AddNew Page where he has some lables and textboxes to AddNew user,

Now what i want to do is in the AddNew Page i want to show All the RoleNames in a DropDown so that admin can select in which role the user has to be....and i want to retrieve the selected data

this is my model class

         public class ResourceModel
{
    public static List<ResourceModel> GetList { get; set; }
    public Int16 EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public string EmployeeEmailId { get; set;}
    public string GroupName { get; set; }
    public string EmployeePassword { get; set; }

}

this is my Controller

            [AcceptVerbs(HttpVerbs.Get)]
     public ActionResult AddNew()
    {

        ViewBag.Roles = new SelectList(GetRoles(),"RoleID","RoleName");           
        return View();
    }
    //
    //Geting All Roles In a GetRoles()/
    //
      public static GetRoles()
      {

        SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True");
        SqlCommand Cmd = new SqlCommand("Select GroupId,EmplopyeeRole from  EmployeeGroup", conn);
        conn.Open();
        SqlDataAdapter da = new SqlDataAdapter(Cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            //roles.Add(new SelectListItem{.Value=i,.Text=i};                   
            var model = new ResourceModel();
            model.RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]);
            model.RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString();
            //roles.Value=Convert.ToString( model.RoleId);
            //roles.Text=model.RoleName;
        }
        conn.Close();
          return ds ;
      }

what i have to return in the above code

this is my AddNew Aspx Page

     <div>
    <% using (Html.BeginForm())
  { %>
  <%-- <form action="Create.aspx" method="post"></form>--%>
   <%:Html.ValidationSummary(true)%>
     <fieldset>
   <legend style="color:Orange; font-weight:bolder;">AddNew Project</legend>

    <div class="editor-label" style="color:Orange; font-weight:bolder;">
        <%: Html.LabelFor(model => model.EmployeeName)%>
    </div>
    <div class="editor-field">
       <%:Html.EditorFor(model => model.EmployeeName)%>
      <%: Html.ValidationMessageFor(model => model.EmployeeName)%>
    </div>

    <div class="editor-label" style="color:Orange; font-weight:bolder;">
       <%:Html.LabelFor(model => model.EmployeeEmailId)%>
    </div>
    <div class="editor-field">
       <%:Html.EditorFor(model => model.EmployeeEmailId)%>
       <%:Html.ValidationMessageFor(model => model.EmployeeEmailId)%>
    </div>
    <div class="editor-label" style="color:Orange; font-weight:bolder;">
    <%:Html.LabelFor(model => model.EmployeePassword)%>
    </div>
    <div class="editor-field">
    <%:Html.EditorFor(model => model.EmployeePassword)%>
    <%:Html.ValidationMessageFor(model => model.EmployeePassword)%>
    </div>
      <div class="editor-label" style="color:Orange; font-weight:bolder;">
    <%:Html.LabelFor(model => model.GroupName)%>
    </div>
    <div class="editor-field">
    <%:Html.EditorFor(model => model.GroupName)%>
    <%:Html.ValidationMessageFor(model => model.GroupName)%>
    <p>
        <input type="submit" value="Create" style="color:Orange; font-weight:bolder;"/>
    </p>
    </fieldset>
    <%} %>        
  </div>

Can any one help me in doing this please in MVC3.... i have to show the RoleNames In a DropDown I have to retreive the value selected in my [AcceptVerbs(HttpVerbs.Post)] in controller....any ideas please

i have a store Procedure for MY [AcceptVerbs(HttpVerbs.Post)] where with the selected dropdown value i will insert the RoleID of the RoleName In Db

     Create Procedure InsertEmplyoee
       (
       @EmployeeName varchar(50),
       @EmployeeEmailId varchar(50),
      @EmployeePassword varchar (50),
       @GroupName varchar (50)
          )
       as
       begin
       insert into EmployeeDetails   (EmployeeName,EmployeeEmailId,EmployeePassword,GroupId) values 
    (@EmployeeName,@EmployeeEmailId,@EmployeePassword,(select GroupId from   EmployeeGroup where EmplopyeeRole=@GroupName ))

end go

Upvotes: 1

Views: 4260

Answers (2)

Mohayemin
Mohayemin

Reputation: 3870

Make your Get Action Like this:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddNew()
{
        ViewBag.RoleId = new SelectList(GetRoles(), "RoleID", "RoleName");
        return View();
}

GetRoles should return a list of Role

In your view:

@Html.DropDownList("RoleId")

Edit: Explanation

Html.DropDownList method will search ViewBag (ViewData actually) for a List of SelectListItem with name RoleId and create the DropDown list with that. You need not explicitly specify the list yourself.

Edit: Correcting GetRoles

GetRoles method should be like this:

public static List<Role> GetRoles() {
    SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True");
    SqlCommand Cmd = new SqlCommand("Select GroupId,EmplopyeeRole from  EmployeeGroup", conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(Cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);

    List<Role> allRoles = new List<Role>();
    for(int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) {
        Role role = new Role {
            RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]),
            RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString()
        };

        allRoles.Add(role);
    }
    conn.Close();
    return allRoles;
}

I have always worked with EntityFramework. Why don't you go with that or some other ORM?

Upvotes: 0

The Muffin Man
The Muffin Man

Reputation: 20004

Think about how you are going to POST the selected role id back to the server.

Instead of public static List<ResourceModel> GetList { get; set; } use public int RoleId {get;set;}. You can't create an @Html.DropDownListFor for a List<T>, that wouldn't make sense, you're just posting a single value back.

Next make a method in your model that returns an IEnumerable of SelectListItem.

public static IEnumerable<SelectListItem> GetRoles()
    {
        var roles = //However you plan to get this data from db
        return roles.Select(o => new SelectListItem
                                     {
                                         Value = o.RoleID,
                                         Text = o.RoleName
                                     });
    } 

Finally in your view:

@Html.DropDownListFor(x=> x.RoleId, ResourceModel.GetRoles())

Upvotes: 1

Related Questions