add checked checkboxes to list in ViewModel

2019-08-06 22:12发布

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

2条回答
Emotional °昔
2楼-- · 2019-08-06 23:09

So i want all the checked categories to be in the list.

With little change in the ViewModel, you can get the checked values on submit as shown below -

Let your Models be like this -

public class CheckboxlistViewModel
{
    public int UserId { get; set; }
    public string JokeTitle { get; set; }
    public string JokeText { get; set; }
    public List<Categorie> categories { get; set; }
}

public class Categorie
{
    public string Category { get; set; }
    public bool IsSelected { get; set; }
}

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 -

    public ActionResult Index()
    {
        CheckboxlistViewModel model = new CheckboxlistViewModel();
        model.categories = new List<Categorie>();
        model.categories.Add(new Categorie() { Category = "Chuck Norris", IsSelected = false });
        model.categories.Add(new Categorie() { Category = "One Liner", IsSelected = false });
        return View(model);
    }

And form is as shown below -

    @model MVC.Controllers.CheckboxlistViewModel

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>

    <div>
    @using (Html.BeginForm("Submit", "Checkboxlist",FormMethod.Post))
    {
        for (int i = 0; i < Model.categories.Count; i++)
        {
            @Html.HiddenFor(m => m.categories[i].Category)
            @Html.CheckBoxFor(m => m.categories[i].IsSelected) @Html.Label(Model.categories[i].Category)
        }
        <input type="submit" value="Submit"/>
    }
    </div>

Now when we click the submit button it will hit below Action -

    public ActionResult Submit(CheckboxlistViewModel model)
    {
        return null;
    }

And if we check the returned model we get selected checkboxes as boolean values as shown below. enter image description here

NOTE: If you want to persist Checkbox text, then add hiddenfield for Category field in the for loop.

查看更多
在下西门庆
3楼-- · 2019-08-06 23:16

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 :)

查看更多
登录 后发表回答