将值传递到 mvc 视图中的下拉列表
我是 MVC 编程的新手。我将其他数据库表中的值传递到我的编辑并创建视图以填充一些下拉列表。效果很好。我的控制器中有这样的代码用于编辑和创建:
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);
我想将 select 语句移动到存储库以使事情变得更干净,这样我就不会在编辑和创建中重复相同的选择。
ViewData["customer"] = orderRepository.GetCustomers();
在Repository
中,GetCustomers
的返回类型应该是SelectListItem
吗?我似乎无法让它发挥作用。
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 Repository
, should the return type of GetCustomers
be SelectListItem
? I can't seem to get it to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 Rob Conery 如何在他的博客上实现它:
http://blog.wekeroad.com/blog/asp-net-mvc-dropdownlist-and-html-attributes/
您可以获取所有客户,然后创建一个 SelectList 并相应地设置您的 ViewData。
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.
尝试以这种方式
在 DDLHelper 等帮助器类上移动此类函数
在 DDLHelper 等帮助器类中编写您的函数
Try on this way
move such kind of function on some helper class like DDLHelper
Write your function in some helper class like DDLHelper
我现在将 SelectList 放在 FormViewModel 类中,并使用部分视图来编辑和创建代码。谢谢大家。
I now have my SelectLists in a FormViewModel class and am using partial views for my edit and create code. Thanks everyone.