0

I have the challenge of adding CheckBoxList of items to MVC 4 view. I have several models in the same the MVC 4 view. So I created the View Model below

public class ArticlesVM
{
    public article articles { get; set; }
    public game games { get; set; }        
    public gallery mgallery { get; set; }
    public team teams { get; set; }

    public ArticlesVM()
    {
        Teams = new List<TeamVM>();
    }
    public List<TeamVM> Teams { get; set; }
}

to include 4 models as it properties. I then created a view where each of the properties can be used independently as follows:

@model TeamBuildingCompetition.ViewModels.ArticlesVM

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout_new.cshtml";
}

<h2>Index</h2>

@using (Html.BeginForm("Create", "TBCArticles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4></h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.articles.featuredImage, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.TextBoxFor(model => model.articles.featuredImage, new { @type = "file" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.games.gameName, "Select a Game", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.DropDownList("gameID", (IEnumerable<SelectListItem>)ViewBag.gameList, "Select Game", new { @class = "form-control" })
            </div>
        </div>

        <div class="form-group">
            @Html.HiddenFor(model => model.teams.teamID)
            @Html.HiddenFor(model => model.teams.teamName)
            @Html.DisplayFor(model => model.teams.teamName)
            <div class="col-md-8">
                @for(int i = 0; i < Model.Teams.Count; i++){
                    @Html.HiddenFor(model => model.Teams[i].ID)
                    @Html.CheckBoxFor(model => model.Teams[i].IsSelected)
                    @Html.LabelFor(model => model.Teams[i].IsSelected, Model.Teams[i].TeamName)
                }
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.articles.articleTitle, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.articles.articleTitle, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.articles.articleTitle, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.articles.articleContent, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.articles.articleContent, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.articles.articleContent, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.mgallery.picturePath, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-8">
                @Html.TextBoxFor(model => model.mgallery.picturePath, new { @type = "file", @multiple = "true" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-8">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Here is my TeamVM model below:

public class TeamVM
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Please Enter Your Team Name")]
    [Display(Name = "Team Name")]
    public string TeamName { get; set; }

    [DisplayName("Team Picture")]
    [ValidateFile]
    public HttpPostedFileBase TeamPicture { get; set; }

    [Required]
    [Display(Name = "Description")]
    public string Description { get; set; }

    [Required(ErrorMessage = "Please Enter Team Content")]
    [Display(Name = "Content")]
    [MaxLength(500)]
    public string Content { get; set; }

    public bool IsSelected { get; set; }
}

Added the following to my controller action:

    [HttpGet]
    public ActionResult Index(ArticlesVM model)
    {
        model = new ArticlesVM ();
        model = new ArticlesVM();
        var teamList = (from p in db.teams
                     select new TeamVM()
                     {
                         ID = p.teamID,
                         TeamName = p.teamName,
                         IsSelected = p.IsSelected
                     });
        model.Teams = teamList.ToList();

        ViewBag.gameList = new SelectList(db.games, "gameID", "gameName");
        return View(model);
    }

And now have a null reference error in this portion of the view:

    <div class="form-group">
        @Html.HiddenFor(model => model.teams.teamID)
        @Html.DisplayFor(model => model.teams.teamName)
        <div class="col-md-8">
            @for(int i = 0; i < Model.Teams.Count; i++){
                @Html.HiddenFor(model => model.Teams[i].ID)
                @Html.CheckBoxFor(model => model.Teams[i].IsSelected)
                @Html.LabelFor(model => model.Teams[i].IsSelected, Model.Teams[i].TeamName)
            }
        </div>
    </div>
Guzzyman
  • 561
  • 6
  • 16
  • 37
  • 1
    `CheckBoxListFor()` is not part of MVC. Show the extension method your using. And what is the `teamName` property of `teams`? –  Oct 20 '15 at 21:17
  • @StephenMuecke: I agree with you. The teamName property of teams is of the type string. Or how do you mean? The Idea here is to have the teams in Checkbox because when writing the article for a game like football, I want the ability to choose the teams involved hence, the need for Checkbox...good morning – Guzzyman Oct 21 '15 at 07:19
  • 1
    If you wanting to select multiple teams using checkbox, then you need a collection, not `string`. And `CheckBoxFor()` binds to a `boolean` property. Not clear exactly what you wanting to do, but [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) may guide you - its a UI for selecting roles associated with a user –  Oct 21 '15 at 07:30
  • @StephenMuecke: Thanks for your response. I have followed it strictly without getting any result as the page is not displaying any checkbox. I already have a TeamVM and a GameVM in my ViewModel folder. Let me give you an idea of what I have. I have about a model with properties from 4 different models namely article, games, team and gallery. They all have their respective views in the view page. The challenge I have is I've not been able to display the checkboxes for the teams. – Guzzyman Oct 21 '15 at 14:19
  • @StephenMuecke: I have updated my questions and also adapted my code to the resource you sent me however, I'm having null reference error in the view. – Guzzyman Oct 21 '15 at 17:06
  • 1
    Your controller action `public ActionResult Create(int ID)` does not seem relevant (it returns a `TeamVM` model, but the view your referring to has a model which is `ArticlesVM`). Have you shown the wrong controller method? –  Oct 21 '15 at 21:44
  • 1
    And if your getting a `null reference error` its because the value of your property `List Teams` is `null` (your need to initialize it an add items to it). But your `ArticlesVM` model is very confusing. You have a property `team teams` and another one `List Teams` which makes no sense. –  Oct 21 '15 at 21:47
  • @StephenMuecke: I'm really so confused. How else can this be done. I followed your resource and maybe I don't have a very good understanding of how to adapt it to my code. When I tried it separately, it didn't show any checkbox. and now it's not showing any checkbox after a few changes. – Guzzyman Oct 22 '15 at 08:31
  • 1
    Start by showing the GET method that generates the view you have shown. –  Oct 22 '15 at 08:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/93050/discussion-between-guzzyman-and-stephen-muecke). – Guzzyman Oct 22 '15 at 08:54

0 Answers0