MvcCheckBoxList for MVC3

Written by stevey on May 31st, 2012

As of today, there is not existing Html exentension for CheckBoxList. You can find @Html.CheckBoxFor but you don’t see @Html.CheckBoxListFor<>, untill, you download and install third party dll or build your own. Today I found one that you can get from NuGet, by reading up article at CodeProject http://www.codeproject.com/Articles/292050/MVC3-Html-CheckBoxList-custom-extension

MVC3 @Html.CheckBoxList extension isntalled from NuGet:

PM> install-package MvcCheckBoxList
Successfully installed ‘MvcCheckBoxList 1.4.2.3′.
Successfully added ‘MvcCheckBoxList 1.4.2.3′ to ETEF.Web.

 

Once MvcCheckBoxList was intalled, it shows up in the project reference as “MvcCheckBoxList”, no particular namespace.
How to use it?

On view:
<div>
<div>
<h3>Roles</h3>
@{
var roles = Model.AvailableRoles.Select(r=>new SelectListItem{Value=r.RoleName,Text=r.RoleName}).ToList();

}

@Html.CheckBoxList(“roles”,roles)
</div>
</div>

on controller:

how to intercept the checkboxes that are selected?
After user clicks on Submit button, the checked boxes were posted as an array of strings. Example in my ETEF.Web WeblinkController code:

[HttpPost]
public ActionResult EditLink(WeblinkModel model, string[] roles)
{

using (ETEF.Data.Repositories.AccessControlRepository acr = new Data.Repositories.AccessControlRepository(GlobalSettings.Database.EntitiesConnectionString))
{
Weblink lnk = new Weblink();
lnk.LinkID = model.WebLinkID;
lnk.LinkText = model.LinkCaption;
lnk.LinkTypeID = model.LinkTypeID;
lnk.NavigateUrl = model.NavigateUrl;
lnk.Roles = GlobalFunctions.ConverArrayToString(roles);
lnk.StatusID = 1;
lnk.DisplayOrder = model.DisplayOrder;
lnk.Description = model.Description;
//lnk.ImageUrl = model.ImageUrl;
int ret = acr.SaveWeblink(lnk);
if (ret > 0)
model.Message = DisplayMessage(“Success”, “Form data has been saved successfully.”, MessageBoxTypes.Success);
else
model.Message = DisplayMessage(“Problem”, “Form data was not saved successfully. Please check your input and try it again.”, MessageBoxTypes.Error);

if (model.WeblinkTypes == null)
{
model.WeblinkTypes = acr.GetWeblinkTypes();
model.AvailableRoles = acr.GetAvailableRoles();

}

}
return View(model);

}

 

Leave a Comment