passing values to a dropdownlist in an mvc view
-
21-09-2019 - |
Question
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.
Solution 3
I now have my SelectLists in a FormViewModel class and am using partial views for my edit and create code. Thanks everyone.
OTHER TIPS
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.
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();
}