在 foreach 循环中获取值
我试图列出所有“用户组”,如果“用户组价格”中存在值,则将其显示在文本框中。但我不确定如何获取该值。
<% foreach (var item in Model.Usergroups)
{
var price = Model.BookingObject.UsergroupPrices.Where(x => x.UsergroupID == item.UsergroupID).Select(x => x.Price);
%>
<tr>
<td><%= Html.Hidden("UsergroupIDPrice", item.UsergroupID) %><%= item.UsergroupName %>:</td>
<td><%= Html.TextBox("UsergroupPrice", price) %></td>
</tr>
<% } %>
价格是十进制的,如果用户组没有任何价格,则可能为空。
TIA
/莱塞
I'm trying to list all "Usergroups", and if a value exists in the "UsergroupPrices" show it in the textbox. But I'm not sure how to get hold of the value.
<% foreach (var item in Model.Usergroups)
{
var price = Model.BookingObject.UsergroupPrices.Where(x => x.UsergroupID == item.UsergroupID).Select(x => x.Price);
%>
<tr>
<td><%= Html.Hidden("UsergroupIDPrice", item.UsergroupID) %><%= item.UsergroupName %>:</td>
<td><%= Html.TextBox("UsergroupPrice", price) %></td>
</tr>
<% } %>
Price is decimal, and may be null if usergroup doesnt have any price.
TIA
/Lasse
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑您只是在寻找
Single
或可能SingleOrDefault
:(转换为
decimal?
是为了使SingleOrDefault
> 如果没有找到匹配项,则返回 nulldecimal?
值而不是 0。)请注意,您当前的代码将进行大量数据库查询,假设这些查询实际上与数据库上下文相关联。您可能应该在控制器中而不是视图中执行这些查询...在控制器中获取所需的所有数据,并以最简单的方式将其放入模型中以便视图显示。
I suspect you're just looking for
Single
or possiblySingleOrDefault
:(The cast to
decimal?
is to makeSingleOrDefault
return a nulldecimal?
value instead of 0 if there's no match found.)Note that your current code will be making lots of database queries though, assuming these are actually associated with database contexts. You should probably be doing these queries in the controllers, not the view... Fetch all the data you need in the controller, and put it in the model in the simplest fashion for the view to display.
您需要选择一条记录:
然后您可以测试价格是否为空。
话虽这么说,我必须说你所做的事情是错误的。获取数据不是视图的责任。这应该由控制器来完成。控制器应该填充视图模型并将该模型传递给视图。该视图模型包含视图所需的所有必要属性,因此您只需在视图内显示它们即可。 这样的代码不属于视图。
因此,我强烈建议您将此逻辑移至控制器中,因为现在您违反了 MVC 模式。
You need to select a single record:
and then you can test if price is null.
This being said I must say that what you are doing is wrong. It is not the view's responsibility to fetch data. This should be done by the controller. The controller should populate a view model and pass this model to the view. This view model contain all the necessary properties required by the view so that inside the view you only have to show them. Code like this doesn't belong to a view.
So I would more than strongly recommend you deporting this logic into the controller as right now you are violating the MVC pattern.