Asp.Net MVC4 Display CheckboxList

前端 未结 2 471
耶瑟儿~
耶瑟儿~ 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 categories = ViewBag.Categories;
    }
    

    and then replace this

        
    @Html.LabelFor(model => model.CategoryId)
    @Html.EditorFor(model => model.CategoryId) @Html.ValidationMessageFor(model => model.CategoryId)

    for this

        
    @foreach(var c in categories) { }

    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");
    }
    

提交回复
热议问题