Gareth
Gareth

Reputation: 5243

MVC Update IList<> in a Form

I'm struggling to understand with ASP.NET MVC (5.2) C# and Entitiy Framework coding how I should be approaching this task.

My model looks like this:

public class CatsViewModel
{
    public CatRateModel CatRateModel { get; set; }
    public IList<CatBreedList> CatBreedList { get; set; }
}

public class CatRateModel
{
    public int CatRateModelId { get; set; }
    public decimal CostToFix1 { get; set; }
    public decimal CostToFix2 { get; set; }
    public IList<RatesCatBreeds> RatesCatBreeds { get; set; }
}

public class CatBreedModel
{
    public int CatBreedModelId { get; set; }
    public int CatBreed { get; set; }
}

public class CatBreedList
{
    public int BreedId { get; set; }
    public int Breed { get; set;}
}

public class RatesCatBreeds
{
    public int RatesCatBreedsId { get; set; }
    public CatBreedModel CatBreedModel { get; set; }
    public decimal CatBreedRate { get; set; }
}

Using a view with a form in it, I'm trying to serve a page where the user can update the values including all of the breeds in CatBreedModel. There's a few different breeds in the table that sits in the CatBreedModel context.

The list of breeds is populated in the controller like so:

CatsContext db = new CatsContext();

CatViewModel vm = new CatViewModel()
{
    CatRateModel = (from c in db.CatRateModel
                    select c
                    ).FirstOrDefault,
    CatBreedList = (from cb in db.CatBreeds
                    select new CatBreedList
                    {
                        BreedId = cb.CatBreedId,
                        Breed = cb.CatBreed
                    }).ToList()
};

vm is passed into the view with return View(vm);

My view looks like:

@Html.EditorFor(model => model.CatRateModel.CostToFix1)
@Html.EditorFor(model => model.CatRateModel.CostToFix2)
@foreach(var CatBreed in Model.CatBreeds)
{
    //How do I put an editor here for each breed in the list?!
}

How can I display an @Html.EditorFor() for each cat breed returned into the list?

Upvotes: 1

Views: 374

Answers (1)

Alan Tsai
Alan Tsai

Reputation: 2525

You would use a for loop in order for model binding to work when post back, such as

@for (int i = 0; i < Model.CatBreeds.Count; i++)
{
    @Html.EditorFor(x => Model.CatBreeds[i].CatBreed)
    @Html.HiddenFor(x => Model.CatBreeds[i].CatBreedModelId)
}

when post back, in your controller, your CatBreeds should be filled (by model binding) with data from the form.

Extra note

The reason of using for loop instead of foreach loop is because creating the index for model binding to work.

For more info on this, checkout this great post on list binding http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

Upvotes: 2

Related Questions