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
I suspect you’re just looking for
Singleor possiblySingleOrDefault:(The cast to
decimal?is to makeSingleOrDefaultreturn 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.