Morning all.
I can see this has been discussed elsewhere but was wondering if anything had change or things made simpler in MVC 4 for simpletons like me?!
Right ok, I have got it sorted - hurrah! As you can see from the comments, there were a few issues that came up but please find below the complete solution which DOES work :D
Model
public class CorporateDetails
{
public Guid? Id { get; set; }
[Key]
public int CorporateDetailId { get; set; }
public int[] EmsId { get; set; }
}
public class EmsType
{
[Key]
public int EmsId { get; set; }
public string EmsName { get; set; }
public virtual ICollection EmsTypes { get; set; }
}
Controller
public ActionResult Create()
{
CorporateDetails corporatedetails = new CorporateDetails();
ViewBag.EmsId = new MultiSelectList(db.EmsTypes, "EmsId", "EmsName");
return View(corporatedetails);
}
Extension (placed in a folder in the root of the project)
public static MvcHtmlString CheckBoxListFor(this HtmlHelper htmlHelper, Expression> expression, MultiSelectList multiSelectList, object htmlAttributes = null)
{
//Derive property name for checkbox name
MemberExpression body = expression.Body as MemberExpression;
string propertyName = body.Member.Name;
//Get currently select values from the ViewData model
TProperty[] list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
//Convert selected value list to a List for easy manipulation
List selectedValues = new List();
if (list != null)
{
selectedValues = new List(list).ConvertAll(delegate(TProperty i) { return i.ToString(); });
}
//Create div
TagBuilder divTag = new TagBuilder("div");
divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
//Add checkboxes
foreach (SelectListItem item in multiSelectList)
{
divTag.InnerHtml += String.Format("",
propertyName,
item.Value,
selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
item.Text);
}
return MvcHtmlString.Create(divTag.ToString());
}
Extension registered in web config of the Views
View
@model Valpak.Websites.HealthChecker.Models.CorporateDetails
@{
ViewBag.Title = "Create";
}
Create
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
}
@Html.ActionLink("Back to List", "Index")
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Which gives me a lovely list of check boxes. Hurrah!
Thanks Darin for your help, I've marked this as the answer but +50 for your time and effort.