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