mardi 28 juin 2016

How to show a unique image for each checkbox item?

my MVC application has a few checkbox items, however, I need to show unique images for each checkbox item, each item is unique so a unique image should too.

Here's what I tried:

View(Index.cshtml):

//MULTIPLE CHECK BOX
for (int i = 0; i < Model.CheckBoxItems.Count; i++) //this line throws an exception (null)
{
    <img src="@Url.Content(Model.CheckBoxItems[i].ImageUrl)" />
    <div>

        @Html.HiddenFor(m => m.CheckBoxItems[i].CBName)
        @Html.LabelFor(l => l.CheckBoxItems[i].CBIsSelected, Model.CheckBoxItems[i].CBName)

        @Html.CheckBoxFor(r => r.CheckBoxItems[i].CBIsSelected, false);
    </div>
}

Controller(HomeController.cs):

 [HttpGet]
    public ActionResult Index()
    {
        ModelVariables model = new ModelVariables()
        {       
            CheckBoxItems = Repository.CBFetchItems()        
        };
        return View(model);
    }

Model(ModelVariables.cs):

  public class ModelVariables
{
    //CHECKBOX
    public List<Item> CheckBoxItems { get; set; } 
}


public class Item
{
    public string CBName { get; set; }
    public bool CBIsSelected { get; set; }
    public string ImageUrl { get; set; }
}

public static class Repository
{   
    public static List<Item> CBFetchItems()
    {
        return new List<Item>()
        {
            new Item(){  CBName = "Girls?" },
            new Item(){  CBName = "Dudes?" },
            new Item(){  CBName = "Animals?" },
            new Item() { ImageUrl  = "~/Assets/ass.PNG"}
        };
    }     
}

When you copy/paste this code and run it, you will get a null exception error.




Aucun commentaire:

Enregistrer un commentaire