Jen143
Jen143

Reputation: 835

CheckBox implementation

I would like to have a checkbox for my Online_Ballot, where a checkbox contains of candidates where a voter could vote for a specific candidates.

Below is my code.

CandidatesViewModel.cs

public class CandidatesViewModel
{
    public IEnumerable<candidates> AvailableCandidates { get;set; }
    public IEnumerable<Candidates> SelectedCandidates { get; set; }
    public PostedCandidates PostedCandidates { get; set; }
}

public class PostedCandidates
{
    public string[] CandidatesId { get; set; }
}

Candidates.cs

public class Candidates
{
    public int candidates_info_id { get; set; }
    public string candidates_fullname { get; set; }
    public object Tags { get; set; }  
    public bool IsSelected { get; set; }
}

Controller

public ActionResult Votation(PostedCandidates PostedCandidates)
{
    return View();
}

View

@Html.CheckBoxListFor(x => x.PostedCandidates.CandidatesId,  
                  x => x.AvailableCandidates,      
                  x => x.candidates_info_id,                    
                  x => x.candidates_fullname,                
                  x => x.SelectedCandidates)  

But when I tried to run this code, an error is displayed:

'System.Collections.Generic.IEnumerable' does not contain a definition for 'PostedCandidates' and no extension method 'PostedCandidates' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)

Upvotes: 1

Views: 72

Answers (1)

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

You are declaring model of type IEnumerable<Online_Ballot.Models.CandidatesViewModel> and using it like you are having an instance not a collection.

you either need to change your model declaration to following (assuming you are passing single instance of type CandidatesViewModel to view from controller):

@model Online_Ballot.Models.CandidatesViewModel

or you can change checkbox list generation to something like this (assuming you are passing collection to the view from controller and that collection is having only one element).

@Html.CheckBoxListFor(x => x.FirstOrDefault().PostedCandidates.CandidatesId,  
              x => x.FirstOrDefault().AvailableCandidates,      
              x => x.FirstOrDefault().candidates_info_id,                    
              x => x.FirstOrDefault().candidates_fullname,                
              x => x.FirstOrDefault().SelectedCandidates)

Although I would recommend you to go with change model declaration.

Update

I also noticed you are not passing instance of your view model to view.

public ActionResult Votation(PostedCandidates PostedCandidates)
{
    CandidatesViewModel vm = new CandidatesViewModel();
    //process or fill your viewmodel here.
    return View(vm);
}

Upvotes: 1

Related Questions