I have an ASP.NET MVC 3 (Razor) website, and a (simplified) model called Review:
public class Review
{
public int ReviewId { get; set; }
public bool RecommendationOne
{
// hook property - gets/set values in the ICollection
}
public bool RecommendationTwo { // etc }
public ICollection<Recommendation> Recommendations { get; set; }
}
Recommendation is as follows:
public class Recommendation
{
public byte RecommendationTypeId
}
I also have an enum called RecommendationType, which i use to map the above recommendation to. (based on RecommendationTypeId).
So to summarize - a single Review has many Recommendations, and each of those Recommendations map to a particular enum type, i expose hook properties to simplify model-binding/code.
So, onto the View:
@Html.EditorFor(model => model.Recommendations, "Recommendations")
Pretty simple.
Now, for the editor template, i want to display a checkbox for each possible RecommendationType (enum), and if the model has that recommendation (e.g on edit view), i check the box.
Here's what i have:
@model IEnumerable<xxxx.DomainModel.Core.Posts.Recommendation>
@using xxxx.DomainModel.Core.Posts;
@{
Layout = null;
}
<table>
@foreach (var rec in Enum.GetValues(typeof(RecommendationType)).Cast<RecommendationType>())
{
<tr>
<td>
@* If review contains this recommendation, check the box *@
@if (Model != null && Model.Any(x => x.RecommendationTypeId == (byte)rec))
{
@* How do i create a (checked) checkbox here? *@
}
else
{
@* How do i created a checkbox here? *@
}
@rec.ToDescription()
</td>
</tr>
}
</table>
As the comments suggest - i don't know how to use @Html.CheckBoxFor
. Usually that takes an expression based on the model, but i'm how sure how to bind to the hook property based on the currently looped enum value. E.g it needs to dynamically do @Html.CheckBoxFor(x => x.RecommendationOne)
, @Html.CheckBoxFor(x => x.RecommendationTwo)
, etc.
The current solution i have (which works), involves manually constructing the <input>
(including hidden fields).
But as i'm just getting the hang of editor templates, hoping someone with experience can point me in a "strongly-typed" direction.
Or is there a nicer way (HTML Helper) i can do this?