i have a ProductController which is consists of Create method.
My Model :
public class ProductEntry
{
public Crescent.LinqModel.Product Products
I use this extension:
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, IEnumerable<TProperty>>> expression,
IEnumerable<SelectListItem> multiSelectList,
Object htmlAttributes = null)
{
// Derive property name for checkbox name
var body = expression.Body as MemberExpression;
if (body == null)
return null;
String propertyName = body.Member.Name;
// Get currently select values from the ViewData model
IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
// Convert selected value list to a List<String> for easy manipulation
var selectedValues = new List<String>();
if (list != null)
selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString());
// Create div
var ulTag = new TagBuilder("ul");
ulTag.AddCssClass("checkBoxList");
ulTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
// Add checkboxes
foreach (var item in multiSelectList)
{
ulTag.InnerHtml += String.Format(
"<li><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></li>",
propertyName,
item.Value,
selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
item.Text);
}
return MvcHtmlString.Create(ulTag.ToString());
}
Me too was having a scenario like you and I implemented it using EditorFor by referring this link "ASP.NET MVC - Multiple checkboxes for row selection in HTML table"
For that you need create a EditorTemplate folder and need to add the view with a same name of model. View code like below
@model EditorForSample.Models.ProductViewModel
<tr>
<td class="text-nowrap">@Html.CheckBoxFor(m => m.Selected, new {@class="chkSelect"}) </td>
<td colspan="3">
@Model.Name
@Html.HiddenFor(m => m.Name)
</td>
<td>
@Model.Price
@Html.HiddenFor(m => m.Price)
</td>
Model can be like below.
public class ProductPageViewModel
{
public string Message { get; set; }
public List<ProductViewModel> ProductsList { get; set; }
}
public class ProductViewModel
{
public bool Selected{ get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
And in parent view you can write html like below
.......
<div class="col-md-12">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th><input type="checkbox" id="chkSelectAll" /></th>
<th colspan="3">
Product Name
</th>
<th>
Cost
</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(m => m.ProductsList)
</tbody>
</table>
</div>
.........
Above link has sample project too. I know answer of this question is already accepted but just sharing this. It may help someone. Thanks :-)
<script>
$("#btndownloading").click(function (e) {
var ckebox_value = $("input[name=cmmdLabels]:checked").map(function () {
if ($(this).val() != 0) {
return $(this).val();
}
}).get();
var ckeck_box_length = ckebox_value.length;
if (ckeck_box_length != 0) {
$.ajax({
url: '@Url.Action("dowloadingfile", "dowloading")',
type: "POST",
data: JSON.stringify({ selectionvalue_ck: ckebox_value }),
contentType: "application/json; charset=utf-8",
success: function (data) {
},
}
});
}
else {
alert("Please select at least one File");
}
});
</script>
[HttpPost]
public ActionResult dowloadingfile(string[] selectionvalue_ck)
{
string fileName = "";
for (int j = 0; j < selectionvalue.Length; j++)
{
fileName = selectionvalue_ck[j];
}
}
<input class="cb-element" name="cmmdLabels" value="1.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="2.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="3.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="4.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="5.txt" type="checkbox">
<button id="btndownloading">Download file</button>
Try this:
@Html.HiddenFor(m => Model.pColors[i].Value);
@Html.HiddenFor(m => Model.pColors[i].Text);
@Html.CheckBoxFor(m => Model.pColors[i].Selected);
I normally use below approach when dealing with checkboxes check whether it helps you.
Model:
namespace GateApplication.Models
{
public class Gate
{
public string PreprationRequired { get; set; }
public List<CheckBoxes> lstPreprationRequired{ get; set; }
public string[] CategoryIds { get; set; }
}
public class CheckBoxes
{
public int ID { get; set; }
public string Value { get; set; }
public string Text { get; set; }
public bool Checked { get; set; }
}
}
Controller:
Load CheckBox Value:
public ActionResult Create()
{
List<CheckBoxes> lstchk = new List<CheckBoxes>()
{
new CheckBoxes {Text="coduit", Value="coduit" },
new CheckBoxes {Text="safety", Value="safety" },
new CheckBoxes {Text="power", Value="power" },
new CheckBoxes {Text="access", Value="access" }
};
var model = new Gate
{
lstPreprationRequired=lstchk
};
return View(model);
}
View:
@foreach (var item in Model.lstPreprationRequired)
{
<input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text"/>
<label for="optionId">@item.Text</label>
<br />
}
Now your view shold have list of checkboxes. Now saving CheckBox values to the database.
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Gate gate = new Gate();
TryUpdateModel(gate);
if (ModelState.IsValid)
{
gate.PreprationRequired = Request.Form["CategoryIds"];// here you'll get a string containing a list of checked values of the checkbox list separated by commas
if (string.IsNullOrEmpty(gate.PreprationRequired))//this is used when no checkbox is checked
gate.PreprationRequired = "None,None";
Save();//Save to database
return RedirectToAction("Index");
}
else
{
return View();
}
}
catch
{
return View();
}
}
Now you have below kind of string in your database
safety,power,access
Now fetch the selected values and display the view.
public ActionResult Edit(int id)
{
List<CheckBoxes> lstchk = new List<CheckBoxes>()
{
new CheckBoxes {Text="coduit", Value="coduit" },
new CheckBoxes {Text="safety", Value="safety" },
new CheckBoxes {Text="power", Value="power" },
new CheckBoxes {Text="access", Value="access" }
};
var model = new Gate
{
lstPreprationRequired =lstchk,
CategoryIds = "safety,power,access".Split(',')//here get your comma separated list from database and assign it to the CategoryIds string array, i have used sample text for the values
};
return View(model);
}
View:
@foreach (var item in Model.lstPreprationRequired)
{
<input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text"
@foreach (var c in Model.CategoryIds)
{
if(c == item.Value)
{
<text> checked="checked"</text>
}
}/>
<label for="optionId">@item.Text></label>
}
Let me know if this does not help you.