I'm working on a C# Application, where users can post jokes. These jokes can have multiple categories, like one-liner or chuck norris. So in my view for creating a joke i have multiple checkboxes for the categories.
Currently, when i create a joke, i have to give a list parameter with all the categories in it.
View:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>CreateJokeViewModel</legend>
<div class="editor-field">
@Html.EditorFor(model => model.UserId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.JokeTitle)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.JokeTitle)
@Html.ValidationMessageFor(model => model.JokeTitle)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.JokeText)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.JokeText)
@Html.ValidationMessageFor(model => model.JokeText)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.categories)
</div>
<div class="editor-field">
<table>
@using (var db = new Witze.Context())
{
foreach (Witze.Categorie categorie in db.Categories)
{
<tr>
<td>@Html.CheckBox(categorie.Name)</td>
<td>@Html.Label(categorie.Name)</td>
</tr>
}
}
</table>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
ViewModel:
[HiddenInput(DisplayValue = false)]
public int UserId { get; set; }
[Required]
public string JokeTitle { get; set; }
[Required]
public string JokeText { get; set; }
[Required]
public HashSet<Categorie> categories { get; set; }
Controller:
public ActionResult Create(CreateJokeViewModel viewModel)
{
List<string> list = new List<string> { "ThisIsACategorie" };
var user = db.User.Single(u => u.UserId == viewModel.UserId);
if (ModelState.IsValid)
{
Logik.CreateJoke(viewModel.JokeTitle, viewModel.JokeText, user.UserId, list);
db.SaveChanges();
return RedirectToAction("witze", "user", new { userid = viewModel.UserId });
}
return View(viewModel);
}
So i want all the checked categories to be in the list. I'm pretty new to MVC and i don't quite seem to find an answer...
Thanks
With little change in the ViewModel, you can get the checked values on submit as shown below -
Let your Models be like this -
Observe that there is a property IsSelected associated with Categorie ViewModel. This property helps us to persist checkbox selection when form is submitted.
Now the action which renders the form is as follows -
And form is as shown below -
Now when we click the submit button it will hit below Action -
And if we check the returned model we get selected checkboxes as boolean values as shown below.
NOTE: If you want to persist Checkbox text, then add hiddenfield for Category field in the for loop.
I worked on this month ago and i wanted the same thing you want and i found a solution to it. go to this site it has perfect solution to it http://www.overpie.com/jquery/articles/jquery-get-selected-checkboxes
Up my answer if it works :)