Reputation: 2449
This is my html-
<td>
@{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
@Html.CheckBox(item.Text, false)
<label>@item.Text</label><br />
}
}
</td>
Im Posting this controller as JSON data (form collection). How can i get checkbox's text
and value
in form collection data in controller?
Upvotes: 1
Views: 8900
Reputation: 2449
I managed to get ID by -
@Html.CheckBox(item.Text, false, new {item.Value})
Upvotes: 1
Reputation: 1039398
How can i get checkbox's text and value in form collection data in controller?
The correct approach is to use a view model instead of this IEnumerable<SelectListItem>
. So basically your model could look like this:
public class BrandViewModel
{
public string Text { get; set; }
public bool Checked { get; set; }
}
and then add a property to your main view model (the one your view is strongly typed to) of type IList<BrandViewModel>
:
public IList<BrandViewModel> Brands { get; set; }
and then it's pretty easy:
<td>
@for (var i = 0; i < Model.Brands.Count; i++)
{
@Html.CheckBoxFor(x => x.Brands[i].Checked)
@Html.LabelFor(x => x.Brands[i].Checked, Model.Brands[i].Text)
@Html.HiddenFor(x => x.Brands[i].Text)
}
</td>
and finally you can get rid of any weakly typed FormCollection from your controller action and simply take the view model:
[HttpPost]
public ActionResult SomeAction(IList<BrandViewModel> brands)
{
...
}
or if there are also other properties you need to pass your controller action may take the main view model:
[HttpPost]
public ActionResult SomeAction(MainViewModel model)
{
// the model.Brands collection will be automatically bound here
...
}
Upvotes: 1
Reputation: 3914
First You have to perform post back to server.
@using (Html.BeginForm("actionname", "controller",
FormMethod.Post))
//your code
@{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
@Html.CheckBox(item.Text, false)
<label>@item.Text</label><br />
}
}
<input type="submit" class="k-button" value="Submit" id="btnSubmit" name="btnSubmit" />
}
Now in the controller you will get the values using form collection
[HttpPost]
public ActionResult actionName( FormCollection collection)
{
collection.keys["checkbox"].value ... your code
}
Upvotes: 0