views:

137

answers:

3

I am a newb to MVC programming. I am passing values from other db tables to my edit and create views to populate some dropdownlists. It's working great. I have code like this in my controller for edit and create:

var db = new MyProgramDataContext(); Order order = orderRepository.GetOrder(id); ViewData["customer"] = from c in db.customers select new SelectListItem { Text = c.customer_name, Value = c.customer_name } return View(order);

I want to move the select statement to the Respository to make things a bit cleaner so that I'm not repeating the same selects in Edit and Create.

ViewData["customer"] = orderRepository.GetCustomers();

In the Respository, should the return type of GetCustomers be SelectListItem? I can't seem to get it to work.

+1  A: 

Check out how Rob Conery has implemented it on his blog:

http://blog.wekeroad.com/blog/asp-net-mvc-dropdownlist-and-html-attributes/

You can get all the customers, and then create a SelectList and set your ViewData accordingly.

Jacob R
OK, so I'm now returning the data from Respository as IQueryable and then in the Controller doing:ViewData["customer"] = new SelectList(orderRespository.GetCustomers(), "customer_name", "customer_name", order.customer);That's working. Is it the best way?
RememberME
If it works, continue using it. You can always return to this code in the future if/when you find a better implementation that works for you.
Jacob R
A: 

Try on this way

move such kind of function on some helper class like DDLHelper

<select id="idXYZ" name="XYZ">
  <%= DDLHelper.DDl_order(Model.orderId)%>
</select>

Write your function in some helper class like DDLHelper

    public static string DDl_order(int orderId)
        {
            string format = "<option value=\"{0}\" {2} >{1}</option>";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendFormat(format, "", "--Select--", "");

            List<Models.UrClass> urclass=orderRepository.GetCustomers();

            foreach (var item in client)
            {
                string ordid = item.orderId.ToString().Encrypt();

                if (item.ClientID == orderId)
                    sb.AppendFormat(format, orderid , item.OrdName,selected=\"selected\"");
                else
                    sb.AppendFormat(format, ordid , item.OrdName, "");
            }
            return sb.ToString();
        }
Pankaj
A: 

I now have my SelectLists in a FormViewModel class and am using partial views for my edit and create code. Thanks everyone.

RememberME