从 MVC 可枚举模型中选择单个项目
当使用使用 IEnumerable 的 MVC 3 集合时,有没有办法让小型查询能够查找单个值?我一直在尝试但收效甚微。
我有一组包含描述和设置的设置。问题在于暴露其中一个,因为每个都是独一无二的。我尝试过这样的事情:
var appl = _service.GetSettings(id, app); //Call to service layer & repository
appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login")));
收效甚微(除非我错过了一些东西)。是否可以从可枚举集合中选择一项并将其传递给 ViewBag 或 ViewData 对象?我想做的是如下所示:
var appl = _service.GetSettings(id, app); //Call to service layer & repository
ViewBag.Login = appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login")));
并将其传递给视图,因为我现在有一个将集合与单个值组合在一起的视图。
以下似乎在该视图中有效:
Application Name @Html.TextBox("application_name", @Model.FirstOrDefault().app_name)
但我不确定这是否违反了关注点分离。我在这里走错路了吗?谢谢你!
编辑:这就是我需要的。下面的答案让我非常非常接近+1 +1
ViewBag.Login = appl.Where(a => a.setting_name.StartsWith("Login")).FirstOrDefault().setting_value
when using a MVC 3 collection that uses IEnumerable, is there a way to make small queries work to find single values? I've been experimenting with little success.
I have a collection of settings that have descriptions and settings. The problem is exposing one of them, as each is unique. I've tried something like this:
var appl = _service.GetSettings(id, app); //Call to service layer & repository
appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login")));
With little success (unless I'm missing something). Is it possible to select one item from an enumerable collection and either pass it to a ViewBag or ViewData object? What I would like to do is something like the following:
var appl = _service.GetSettings(id, app); //Call to service layer & repository
ViewBag.Login = appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login")));
And pass this to the view, since I have a view that now combines a collection with single values.
The following seems to work within the view:
Application Name @Html.TextBox("application_name", @Model.FirstOrDefault().app_name)
But I'm not sure if this violates separation of concerns. Am I on the wrong path here? Thank you!
EDIT: Here is what I needed. The answers below got me very very close +1 +1
ViewBag.Login = appl.Where(a => a.setting_name.StartsWith("Login")).FirstOrDefault().setting_value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将选择第一个符合您的条件的对象并返回单个结果或 null
This will select the first object that matches your criteria and return a single result or null