mercredi 13 mai 2020

Asp.net mvc how to add all the checked elements of an checkbox in an IEnumerable?

I have the model Recipe and the model IngredientFilter. The model Recipe has an IEnumerable where I want to add all the checked elements. For a recipe in the New method I display all the checkboxes but when but the IEnumerable is always null.

Recipe model:

 public class Recipe
{
    [Key]
    public int RecipeId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    ......................
    public IEnumerable<IngredientFilter> IngredientFilters { get; set; }

    }

IngredientFilter Model:

public class IngredientFilter
{
    [Key]
    public int IngredientId { get; set; }

    public string IngredientName { get; set; }

    public bool IsChecked { get; set; }
}

New Method Recipe public ActionResult New() { ......

        IEnumerable<IngredientFilter> ing = db.IngredientFilters.ToList();

        Recipe recipe = new Recipe();

        recipe.IngredientFilters = ing;
       ........
        return View(recipe);
    }

New Post Method Recipe

public ActionResult New(Recipe recipe)
    {

        try {


            IEnumerable<IngredientFilter> ing = recipe.IngredientFilters.Where(x => x.IsChecked == true).ToList();
            recipe.IngredientFilters = ing;

            string fileName = Path.GetFileNameWithoutExtension(recipe.ImageFile.FileName);
            string extension = Path.GetExtension(recipe.ImageFile.FileName);
            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            recipe.ImagePath = "~/Image/" + fileName;
            fileName = Path.Combine(Server.MapPath("~/Image"), fileName);
            recipe.ImageFile.SaveAs(fileName);

            db.Recipes.Add(recipe);
            db.SaveChanges();
            ModelState.Clear();
            return RedirectToAction("Index");
        }
        catch(Exception e)
        {
            return View();
        }


    }

Recipe View New

<div>
        @for (int i = 0; i < Model.IngredientFilters.Count(); i++)
        {
        <div>
            @Html.CheckBoxFor(m => Model.IngredientFilters.ElementAt(i).IsChecked)
            @Model.IngredientFilters.ElementAt(i).IngredientName
            @Html.HiddenFor(m => Model.IngredientFilters.ElementAt(i).IngredientId)
            @Html.HiddenFor(m => Model.IngredientFilters.ElementAt(i).IngredientName)

        </div>



Aucun commentaire:

Enregistrer un commentaire