jeudi 4 janvier 2018

Product Model contains list of object - retrieving and displaying checkbox list incorrectly. MVC .NET

I have my product class - edit view and edit get controller method. The view for the check boxes literally displays 'Name' instead of the ingredients name (ie. Cedarwood) - the checkbox should have some items 'selected' as they are set to true in the database.

public class Product
  {

    public Product()
    {
        ProductImages = new List<ProductImage>();
        Ingredients = new List<Ingredient>();
        OrderDetails = new List<OrderDetail>();
    }
    [ScaffoldColumn(false)]
    public int ProductId { get; set; }
    public string Blend { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public List<Ingredient> Ingredients { get; set; }
    [DataType(DataType.Currency)]
    [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")]
    public decimal Price { get; set; }
    [DisplayName("Product Art URL")]
    [StringLength(1024)]
    public string MainPhotoUrl { get; set; }

    [Display(Name = "LegendPhoto")]
    public byte[] LegendPhoto { get; set; }
    public ICollection<ProductImage> ProductImages { get; set; }
    public virtual ICollection<OrderDetail> OrderDetails { get; set; }

}

controller:

 public ActionResult Edit(int? id)
    {
        //get list of ingredients
        var ingredients = db.Ingredients.ToList();


        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Product product = db.Products.Find(id);
        product.Ingredients = db.Ingredients.ToList();
        if (product == null)
        {
            return HttpNotFound();
        }
        return View(product); //product
    }

the view (the rest is fine just the checkbox for ingredients - so only showing it:

                   <div class="form-group">
                @Html.LabelFor(model => model.Ingredients, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @for(var i = 0; i < Model.Ingredients.Count; i++)
                    {
                        @Html.HiddenFor(ing => Model.Ingredients[i].Id)
                        @Html.HiddenFor(ing => Model.Ingredients[i].Name)
                        @Html.HiddenFor(m => m.Ingredients[i].IsSelected)
                        @Html.LabelFor(ing => Model.Ingredients[i].Name, new {htmlAttributes = new {@class = "form-control"}})
                        @Html.CheckBoxFor(ing => Model.Ingredients[i].IsSelected, new {htmlAttributes = new {@class = "form-control"}})

                    }
                    @Html.ValidationMessageFor(model => model.Price, "", new {@class = "text-danger"})
                </div>
            </div>




Aucun commentaire:

Enregistrer un commentaire