Asp.Net MVC4 Display CheckboxList

前端 未结 2 456
耶瑟儿~
耶瑟儿~ 2020-12-28 21:34

I have searched a lot and spend 3 days only for searching and trying different technique (on stackoverflow etc) but I find no solution for implementing checkboxlist in asp.n

相关标签:
2条回答
  • 2020-12-28 22:03

    You need to have an object that will have a list of all categories, for example, you could do this:

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public ActionResult ProjectAdd()
    {
        // Get all categories and pass it into the View
        ViewBag.Categories = db.ListAllCategories();
    
        return View();
    }
    

    in the top of your View

    @model Database.Project
    @{
       // retrieve the list of Categories
       List<Database.Category> categories = ViewBag.Categories;
    }
    

    and then replace this

        <div class="editor-label">
            @Html.LabelFor(model => model.CategoryId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CategoryId)
            @Html.ValidationMessageFor(model => model.CategoryId)
        </div>
    

    for this

        <div class="editor-label">
            <label for="categories">Categories</label>
        </div>
        <div class="editor-field">
            @foreach(var c in categories) {
    
            <label class="checkbox">
                <input type="checkbox" name="categories" value="@c.CategoryId"> @c.CategoryName
            </label>
    
            }
        </div>
    

    back in your Controller

    [HttpPost]
    [Authorize(Roles = "Admin")]
    public ActionResult ProjectAdd(Database.Project model, int[] categories)
    {
        if(ModelState.IsValid) {
    
            // fill up categories
            db.InsertAndSaveProject(model, categories);
    
        }
    
        ...
    
        return redirectToView("ProjectAdd");
    }
    
    0 讨论(0)
  • 2020-12-28 22:23

    Answer suggested by @balexandre above works great. However, I used following HTML Extension for CheckBoxList.

    1. CheckboxList in ASP.net MVC4
    2. Source Code:HTML Extension Helper method (Github)

    The Major advantage of using this helper method is clean code and better readability. E.g.

    @Html.CheckBoxListFor(model => model.SelectedItems, Model.AllItems)
    
    0 讨论(0)
提交回复
热议问题