I have a publishers table and I have titles table. I am using Entity Framework v4.1. A publisher entity has titles property and it signifies how many titles this particular publisher has published (I am using pubs database). I want to create a checkbox list where all the titles are shown (all records of titles table) and the titles which this publisher has published should be checked. How can I do that?
I am only able to produce a DropDownlist so far using this code:
<tr>
<td>
Titles
</td>
<td>
@Html.DropDownListFor(p => p.titles.ToList()[0], new SelectList(ViewBag.titles, "title_id", "notes"))
</td>
</tr>
How can I convert this to checkbox list?
Thanks in advance :)
EDIT:
After reading Brian's
post, I made some progress however when I submit the form no values are found:
I created a partial class of title:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCWebApp.Models
{
public partial class title
{
public int Id { get; set; }
public bool IsChecked { get; set; }
}
}
This is my EditorTemplate for checkbox:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MVCWebApp.Models.title>" %>
<%= Html.HiddenFor(x => x.Id)%>
<%= Html.CheckBoxFor(x => x.IsChecked)%>
<%= Html.DisplayFor(x => x.title1)%>
<br />
From the page where I need checkboxlist I wrote this code:
<td>
@Html.EditorFor(p => ViewData["titles"])
</td>
This is the actual (highly ineffecient due to nested loop) controller method which renders the page:
public ActionResult Edit(string id)
{
using (PubsEntities entities = new PubsEntities())
{
publisher pub = entities.publishers.Include("titles").Where(p => p.pub_id == id).First();
List<title> titles = entities.titles.ToList();
foreach (var item in pub.titles)
{
title tit = (from titleItem in titles where item.pub_id == titleItem.pub_id select item).First();
tit.IsChecked = true;
}
ViewData["titles"] = titles;
return View(pub);
}
}
I get the master list of titles and those titles are published by a particular publisher is checked. However when the form is posted, the values are all null
This is my update method where the form is posted:
public ActionResult Update(publisher modifiedPub, List<title> selectedTitle )
{
if (!ModelState.IsValid)
return View("Edit", modifiedPub);
using (PubsEntities entities = new PubsEntities())
{
publisher pub = entities.publishers.Where(p => p.pub_id == modifiedPub.pub_id).First();
pub.pub_name = modifiedPub.pub_name;
pub.state = modifiedPub.state;
entities.SaveChanges();
return RedirectToAction("Publishers");
}
}
Here the selectedTitle is null and even in modifiedPub.titles the count is 0. Can anybody tell me where is it wrong?
Thanks in advance :)
P.S: Do we really have to do so much just to get checkboxlist?