Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 3.5 > BOOK: Professional ASP.NET MVC 1.0 ISBN: 978-0-470-38461-9
Password Reminder
Register
Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Professional ASP.NET MVC 1.0 ISBN: 978-0-470-38461-9
This is the forum to discuss the Wrox book Professional ASP.NET MVC 1.0 by Rob Conery, Scott Hanselman, Phil Haack, Scott Guthrie; ISBN: 978-0-470-38461-9
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Professional ASP.NET MVC 1.0 ISBN: 978-0-470-38461-9 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developersí questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
 
 
Thread Tools Display Modes
  #1 (permalink)  
Old February 9th, 2012, 05:35 PM
Authorized User
Points: 95, Level: 1
Points: 95, Level: 1 Points: 95, Level: 1 Points: 95, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2011
Posts: 24
Thanks: 3
Thanked 0 Times in 0 Posts
Default How to use DropDownListfor to lookup vaules from another table?

Hi,

Based on my very limited ASP.net MVC knowledge developing my new app from Nerd Dinner.....

I am trying to achieve something which should be a very common practice. I have 2 tables: Department and Category (1 department to many categories).

When I input a new Category, I want to have a dropdownlist to select a department, then enter the category, and save.

I have managed to get it working but I have to repeat:
Code:
//populate dropdown list with departments
DepartmentRepository departmentRepository = new DepartmentRepository();
var departments = departmentRepository.FindAllDepartment();

IEnumerable<SelectListItem> items = departments
.Select(d => new SelectListItem
{
Value = d.Dept_ID.ToString(),
Text = d.Department1
});


ViewBag.Dept_ID = items;
many times - for create (get and post) and edit (get and post). I am sure there is a short winded way to do this? Also I don't think using ViewBag is the best option for this??

I will have more drop down lists to do and if I have to use this approach, surely it would be very hard for others to maintain?!

Could anyone kindly help me, and perhaps give me a good example to work from? I have already spent a few days googling but there is not a straight forward example.

Below are the codes for my Edit (get and post) in the Category Controller:

Code:
public ActionResult Edit(int id)
{
Category category = categoryRepository.GetCategory(id);

//populate dropdown list with departments
DepartmentRepository departmentRepository = new DepartmentRepository();
var departments = departmentRepository.FindAllDepartment();

IEnumerable<SelectListItem> items = departments
.Select(d => new SelectListItem
{
Value = d.Dept_ID.ToString(),
Text = d.Department1
});


ViewBag.Dept_ID = items;

ViewBag.Mode = "Edit";


return View(new CategoryFormViewModel(category));
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, string button, FormCollection collection)
{
if (button == "cancel")
return RedirectToAction("Index", "Category");

//populate dropdown list with departments
DepartmentRepository departmentRepository = new DepartmentRepository();
var departments = departmentRepository.FindAllDepartment();

IEnumerable<SelectListItem> items = departments
.Select(d => new SelectListItem
{
Value = d.Dept_ID.ToString(),
Text = d.Department1
});
ViewBag.Dept_ID = items;

ViewBag.Mode = "Edit";

Category category = categoryRepository.GetCategory(id);

if (collection["Category.Dept_ID"] != "")
{
category.Dept_ID = Convert.ToInt32(collection["Category.Dept_ID"]);
}
else
{
category.Dept_ID = null;
}

category.Category1 = collection["Category1"];

try
{
UpdateModel(category);
categoryRepository.Save();
return RedirectToAction("Index", new { id = category.Category_ID });
}

catch
{
ModelState.AddModelErrors(category.GetRuleViolatio ns());
return View(new CategoryFormViewModel(category));
}
}
My CategoryFormViewModel is as below:

Code:
//
// ViewModel Classes

public class CategoryFormViewModel
{
//properties
public Category Category { get; private set; }

//Constructor
public CategoryFormViewModel(Category category)
{
Category = category;
}
And in my View I have:

Code:
<p>
<label for="Dept_ID">Department:</label>
<%

if (ViewBag.Mode == "Create")
{
%>
<%=Html.DropDownList("Dept_ID",
(IEnumerable<SelectListItem>)ViewBag.Dept_ID,"--Select One--")%>
<%
}
else
{
%>
<%=Html.DropDownListFor(m => m.Category.Dept_ID, 
(IEnumerable<SelectListItem>)ViewBag.Dept_ID, "--Select One--")%>
<%}
%>
<%=Html.ValidationMessage("Dept_ID", "*")%> 
</p>
Please be patient with me as I am a fluent Classic ASP developer but very new to ASP.NET MVC!

Many thanks in advance.
  #2 (permalink)  
Old February 10th, 2012, 05:24 PM
Friend of Wrox
Points: 742, Level: 10
Points: 742, Level: 10 Points: 742, Level: 10 Points: 742, Level: 10
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2009
Location: Tehran, Iran
Posts: 156
Thanks: 13
Thanked 16 Times in 16 Posts
Default Use session variables

Hi my friend!
I often use session variables instead of using repeatedly database calls.

Code:
private void LoadDepartments()
{
   if(Session["departments"] == null){
        //populate dropdown list with departments
        DepartmentRepository departmentRepository = new DepartmentRepository();
        var departments = departmentRepository.FindAllDepartment();

        IEnumerable<SelectListItem> items = departments
                 .Select(d => new SelectListItem
                 {
                     Value = d.Dept_ID.ToString(),
                     Text = d.Department1
                  });
        Session["departments"] = items;
   }
   ViewBag.Dept_ID = (IEnumerable<SelectListItem>)Session["departments"];
}

Last edited by irProject; February 10th, 2012 at 05:27 PM.
  #3 (permalink)  
Old February 17th, 2012, 06:39 AM
Authorized User
Points: 95, Level: 1
Points: 95, Level: 1 Points: 95, Level: 1 Points: 95, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2011
Posts: 24
Thanks: 3
Thanked 0 Times in 0 Posts
Default How to do this in a helper?

Thank you. Nice codes...however, how can I put this in a helper please? (Sorry, I'm still very new to ASP.NET MVC).

I tried putting the codes in but it wouldn't compile with "private", "Session", "ViewBag"

I would like to call it in a number of places, i.e. whenever I have a dropdown list for department?

Thank you in advance again.

Last edited by bh81; February 17th, 2012 at 07:06 AM.
  #4 (permalink)  
Old February 17th, 2012, 11:05 AM
Friend of Wrox
Points: 742, Level: 10
Points: 742, Level: 10 Points: 742, Level: 10 Points: 742, Level: 10
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2009
Location: Tehran, Iran
Posts: 156
Thanks: 13
Thanked 16 Times in 16 Posts
Smile

Hi there

try this one:

Code:
public class DepartmentHelper{

public static IEnumerable<SelectListItem> GetDepartmentsForList()
{
   if(Session["departments"] == null){
        //populate dropdown list with departments
        DepartmentRepository departmentRepository = new DepartmentRepository();
        var departments = departmentRepository.FindAllDepartment();

        IEnumerable<SelectListItem> items = departments
                 .Select(d => new SelectListItem
                 {
                     Value = d.Dept_ID.ToString(),
                     Text = d.Department1
                  });
        Session["departments"] = items;
   }
   return (IEnumerable<SelectListItem>)Session["departments"];
}

} // Department Helper
and in View:
HTML Code:
<p>
<label for="Dept_ID">Department:</label>
<%

if (ViewBag.Mode == "Create")
{
%>
<%=Html.DropDownList("Dept_ID",
DepartmentHelper.GetDepartmentsForList(),"--Select One--")%>
<%
}
else
{
%>
<%=Html.DropDownListFor(m => m.Category.Dept_ID, 
DepartmentHelper.GetDepartmentsForList(), "--Select One--")%>
<%}
%>
<%=Html.ValidationMessage("Dept_ID", "*")%> 
</p>
I'm not sure about these code, because I use VS2008
__________________
happy every time, happy every where

Reza Baiat
The Following User Says Thank You to irProject For This Useful Post:
bh81 (February 20th, 2012)
  #5 (permalink)  
Old February 20th, 2012, 07:34 AM
Authorized User
Points: 95, Level: 1
Points: 95, Level: 1 Points: 95, Level: 1 Points: 95, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2011
Posts: 24
Thanks: 3
Thanked 0 Times in 0 Posts
Thumbs up You are a star - thank you

Thank you. Exactly what I was looking for.

All are working apart from having to use:

HttpContext.Current.Session["departments"] instead of Session["departments"]

You are a star :)
  #6 (permalink)  
Old March 5th, 2012, 09:42 AM
Authorized User
Points: 95, Level: 1
Points: 95, Level: 1 Points: 95, Level: 1 Points: 95, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2011
Posts: 24
Thanks: 3
Thanked 0 Times in 0 Posts
Default populate dropdown with AD users

Based on the same principle with getting all the departments, I am trying to connect to LDAP and retrieve all the users and populate the drop down list......but the codes below does not work. I can see that it connects to LDAP but it's the

Code:
IEnumerable<SelectListItem> items = allUser
.Select(d => new SelectListItem

                        {
                            Value = result.Properties["cn"][0].ToString();
                            Text = result.Properties["cn"][0].ToString();
                        }
                        HttpContext.Current.Session["ADUsers"] = result;
of the following codes that does not work. Not sure if the return works either. Please can someone shed some light on this please? Thanks in advance.


Code:
namespace FCWorkRequest.Helpers
{
    public class RetriveADInfo
    {
        public static IEnumerable<SelectListItem> GetADUserForList()
        {
            if (HttpContext.Current.Session["ADUsers"] == null)
            {
                try
                {
                    // create LDAP connection object
                    DirectoryEntry myLdapConnection = createDirectoryEntry();

                    // create search object which operates on LDAP connection object
                    // and set search object to only find the user specified

                    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                    search.PropertiesToLoad.Add("cn");

                    // create results objects from search object
                    SearchResultCollection allUsers = search.FindAll();

                    IEnumerable<SelectListItem> items = allUser
.Select(d => new SelectListItem

                        {
                            Value = result.Properties["cn"][0].ToString();
                            Text = result.Properties["cn"][0].ToString();
                        }
                        HttpContext.Current.Session["ADUsers"] = result;
                    }
                }
 
                catch (Exception e)
                {
                    Console.WriteLine("Exception caught:\n\n" + e.ToString());
                }

            }
            return (IEnumerable<SelectListItem>)HttpContext.Current.Session["ADUsers"];
        }

        static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings
            DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://DC=XX,DC=XX", "auser", "apswd");
            ldapConnection.Path = "LDAP://OU=XX,OU=XX,DC=XX,DC=XX";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            //will also need one for LDAP://OU=XX,OU=XX,DC=XX,DC=XX
            return ldapConnection;
        }

    }
}

Last edited by bh81; March 7th, 2012 at 05:59 AM.
  #7 (permalink)  
Old March 5th, 2012, 09:55 AM
Friend of Wrox
Points: 742, Level: 10
Points: 742, Level: 10 Points: 742, Level: 10 Points: 742, Level: 10
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2009
Location: Tehran, Iran
Posts: 156
Thanks: 13
Thanked 16 Times in 16 Posts
Smile

Hi there

linq or labmda expressions are not fully done at creation time. you may need to convert the result to List:

Code:
IEnumerable<SelectListItem> items = allUser
.Select(d => new SelectListItem
                        {
                            Value = result.Properties["cn"][0].ToString();
                            Text = result.Properties["cn"][0].ToString();
                        }
).ToList();
HttpContext.Current.Session["ADUsers"] = result;
List is an IEnumerable. so there is no consern about type conversion
__________________
happy every time, happy every where

Reza Baiat
  #8 (permalink)  
Old March 6th, 2012, 05:13 AM
Authorized User
Points: 95, Level: 1
Points: 95, Level: 1 Points: 95, Level: 1 Points: 95, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2011
Posts: 24
Thanks: 3
Thanked 0 Times in 0 Posts
Default 1 error on the use of .Select

Thank you irProject for you prompt reply. Much appreciated. Now I'm left with 1 error:
Quote:
'System.DirectoryServices.SearchResultCollection' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.DirectoryServices.SearchResultCollection' could be found (are you missing a using directive or an assembly reference?)
The codes are as below now:
Code:
    public class RetriveADInfo
    {
        public static IEnumerable<SelectListItem> GetADUserForList()
        {
            if (HttpContext.Current.Session["ADUsers"] == null)
            {
                try
                {
                    // create LDAP connection object
                    DirectoryEntry myLdapConnection = createDirectoryEntry();

                    // create search object which operates on LDAP connection object
                    // and set search object to only find the user specified

                    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                    search.PropertiesToLoad.Add("cn");
                    
                    // create results objects from search object
                    SearchResultCollection allUsers = search.FindAll();

                    IEnumerable<SelectListItem> items = allUsers
                    .Select(u => new SelectListItem
                        {
                            Value = u.Properties["cn"][0].ToString(),
                            Text = u.Properties["cn"][0].ToString()
                        }).ToList();
                    HttpContext.Current.Session["ADUsers"] = items;
                }

                catch (Exception e)
                {
                    Console.WriteLine("Exception caught:\n\n" + e.ToString());
                }
            }
            return (IEnumerable<SelectListItem>)HttpContext.Current.Session["ADUsers"];
        }

        static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings
            DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://DC=XX,DC=XX", "usr", "pswd");
            ldapConnection.Path = "LDAP://OU=xx,OU=xx,DC=,DC=XX";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;
        }

    }
Also, what do I meant to with the exception? I copied the "Console.WriteLine" from an example.

Many thanks again.

Last edited by bh81; March 7th, 2012 at 05:59 AM.
  #9 (permalink)  
Old March 7th, 2012, 05:53 AM
Authorized User
Points: 95, Level: 1
Points: 95, Level: 1 Points: 95, Level: 1 Points: 95, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2011
Posts: 24
Thanks: 3
Thanked 0 Times in 0 Posts
Default This is working now but hope it is the right approach

I have got it working now and I hope this will help someone. But do let me know if there is a better approach.

Code:
       public static IEnumerable<SelectListItem> GetADUserForList()
        {
            if (HttpContext.Current.Session["ADUsers"] == null)
            {
                try
                {
                    // create LDAP connection object
                    DirectoryEntry myLdapConnection = createDirectoryEntry();

                    // create search object which operates on LDAP connection object
                    // and set search object to only find the user specified

                    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                    search.PropertiesToLoad.Add("cn");

                    // create results objects from search object
                    SearchResultCollection allUsers = search.FindAll();
                    
                    var stagingList = new List<String>();
                    foreach (SearchResult item in allUsers)
                    {
                        if (item.Properties["cn"].Count > 0)
                        {
                            string value = item.Properties["cn"][0].ToString();
                            stagingList.Add(value);
                        }
                    }

                    stagingList.Sort();

                    var mySelect = new SelectList(stagingList);

                    IEnumerable<SelectListItem> items = mySelect
                        .Select(u => new SelectListItem
                        {
                            Value = u.Value,
                            Text = u.Value
                        });

                    HttpContext.Current.Session["ADUsers"] = mySelect;

           }
                catch (Exception e)
                {
                    Console.WriteLine("Exception caught:\n\n" + e.ToString());
                }

            }
            return (IEnumerable<SelectListItem>)HttpContext.Current.Session["ADUsers"];
        }

        static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings
            DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://DC=XX,DC=XX", "usr", "pwd");
            ldapConnection.Path = "LDAP://OU=XX,OU=XX,DC=XX,DC=XX";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            //will also need one for LDAP://OU=Users,OU=XX,DC=XX,DC=XX
            return ldapConnection;
        }

    }
 


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Need to use DropDownListfor to lookup vaules from another table bh81 BOOK: Professional ASP.NET MVC 3 0 February 9th, 2012 09:42 AM
lookup value in table Vince_421 Access 16 February 13th, 2007 08:15 AM
Lookup (Dispatch) Table CNewbie C++ Programming 5 November 2nd, 2004 04:12 PM
Lookup Table Problem mikericc Access VBA 2 January 19th, 2004 07:11 PM
lookup table current field. Squid Access 0 December 21st, 2003 07:08 PM



All times are GMT -4. The time now is 12:55 AM.


Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.