0

I'm using ASP.NET MVC 5 and Entity Framework.

I have these three model classes:

public class SubCat
{
        public int Id { get; set; }
        public string Description { get; set; }

        [ForeignKey("Category")]
        public int CategoryId { get; set; }
        public Category Category { get; set; }
}

public class Item
{
        public Item()
        {
            Images = new HashSet<Image>();
        }

        public int Id { get; set; }
        public string Description { get; set; }

        [ForeignKey("SubCat")]
        public int? SubCatId { get; set; }
        public SubCat SubCat { get; set; }

        //public byte? Image { get; set; }

        [ForeignKey("Images")]
        public int? ImageId { get; set; }
        public ICollection<Image> Images { get; set; }

        public int ItemPoints { get; set; }
        public int? PointsValue { get; set; }

        public string Status { get; set; }

        [Display(Name = "Delivery")]
        public string DeliveryChoice { get; set; }

        public bool? Approved { get; set; }

        public bool? Bartered { get; set; }
}

public class Image
{
        public int Id { get; set; }

        [DisplayName("Upload File")]
        public string Picture { get; set; }

        [NotMapped]
        public HttpPostedFileBase ImageFile { get; set; }

        [ForeignKey("Item")]
        public int? ItemId { get; set; }
        public Item Item { get; set; }
}

When I add a new item, I need to give it a subcategory id in order to show it in the view and here is how I add a new item:

The form:

@using (Html.BeginForm("ItemSubmit", "Orders", FormMethod.Post, new { enctype = "multipart/form-data" }))
                            {
                                <div class="form-group">
                                    @Html.LabelFor(m => m.Item.Description, new { @class = "col-md-2 control-label" })
                                    @Html.TextBoxFor(m => m.Item.Description, new { @class = "form-control" })
                                </div>
                                <br />
                                <div class="form-group">
                                    <div class="col-md-6">
                                        @Html.DropDownListFor(m => m.Category.Id, new SelectList(Model.Categories, "Id", "Description"), "Select Category", new { @class = "form-control", @id = "cats" })
                                    </div>
                                    <div class="col-md-6">
                                        <select id="subs" disabled class="dropdown form-control" name="subCategory">
                                            <option>Select Category First</option>
                                        </select>

                                    </div>
                                    <br />
                                    <br />
                                    <br />
                                    <div class="form-group">
                                        @Html.LabelFor(m => m.Item.Status, new { @class = "col-md-2 control-label" })
                                        @Html.DropDownListFor(m => m.Item.Status, new SelectList(Model.Items, "Status", "Status"), "", new { @class = "form-control" })
                                    </div>
                                    <br />
                                    <div class="form-group">
                                        @Html.LabelFor(m => m.Item.DeliveryChoice, new { @class = "col-md-2 control-label" })
                                        @Html.DropDownListFor(m => m.Item.DeliveryChoice, new SelectList(Model.Items, "DeliveryChoice", "DeliveryChoice"), "", new { @class = "form-control" })
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-1"></div>
                                        <h3><span class="label label-primary">How many points would you suggest for your Item?</span></h3>
                                        <div class="col-md-3"></div>
                                        @Html.TextBoxFor(m => m.Item.ItemPoints, new { @class = "form-control" })
                                    </div>
                                    <div class="form-group">
                                        @Html.LabelFor(m => m.Image.Picture, htmlAttributes: new { @class = "control-label col-md-2" })

                                        <input type="file" name="ImageFile" required>

                                    </div>
                                    <br />
                                    <br />


                                    <div class="row">
                                        <button type="submit" class="btn btn-success">Submit</button>
                                    </div>
                                </div>
                            }

and the controller:

[HttpPost]
        public ActionResult ItemSubmit(Item item, int subCategory, Image imageModel, Order order, ApplicationUser user)
        {
            if (ModelState.IsValid)
            {
                    var sub = _context.SubCats.SingleOrDefault(m => m.Id == subCategory);

                    //Item
                    item.SubCatId = sub.Id;

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



                    //Order
                    order.OrderDate = DateTime.Now;
                    order.TransactionType = "Item Submit";
                    order.UserId = User.Identity.GetUserId();
                    order.Approved = false;
                    order.ItemId = item.Id;


                    _context.Items.Add(item);
                    _context.Images.Add(imageModel);
                    _context.Orders.Add(order);
                    _context.SaveChanges();


            }


            return RedirectToAction("Index","Home");
        }

but when _context.SaveChanges() is called, ef tend to save two copies of the item! one with a subcatid and one wihout a subcatid, and the funny thing is that the image takes the itemid of the item without the subcatid, so when i try to show the item on the view by the image it doesnt show because the item shown must be related to the subcat chosen.

here is the jquery i use in the view:

$(document).ready(function () {
            $(".mybtn").on('click', function () {
                var id = $(this).attr('data-id');
                $("#images").html('');
                $.get("/Items/GetSubById", { ID: id }, function (data) {
                    $("#sub-categories-btns").html(``);
                    for (var i = 0; i < data.length; i++) {
                        $("#sub-categories-btns").append(`
                        <button id="button" type="button" data-id="`+ data[i].Id + `" class="btn btn-success my-subcategory-btn">
                            `+ data[i].Description +`
                        </button>
                    `);
                    }
                });
            });

            $("#sub-categories-btns").delegate(".my-subcategory-btn", 'click', function () {
                var subId = $(this).attr('data-id');
                $("#images").html('');
                $.get("/Items/GetImgaesBySubCategoryId", { ID: subId }, function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $("#images").append(`
                            <div class="form-group col-md-4">
                                <button data-id="`+ data[i].ItemId +`" name="item" class="ItemInfo img-btn"><img src="`+ data[i].Picture +`" width="200" height="200" /></button>
                            </div>
                        `);
                    }
                });
            });

            $("#images").delegate('.img-btn', 'click', function () {
                var imgId = $(this).attr('data-id');
                window.location.href = "/Items/Buy?item=" + imgId;
            });

        });

This is the json i send to the view:

public JsonResult GetSubById(int? ID)
        {
            return Json(_context.SubCats.Where(p => p.CategoryId == ID), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetImgaesBySubCategoryId(int? ID)
        {
            var data = _context.Images.Where(m => m.Item.SubCatId == ID).ToList();
            data.ForEach(img => img.Picture = img.Picture.Replace("~", ""));
            return Json(data, JsonRequestBehavior.AllowGet);
        }

How do i stop it from duplicating??

3
  • Can you show how the method that calls ItemSubmit gets those parameters to pass to it?
    – sellotape
    Dec 4, 2018 at 17:06
  • Just did above the controller
    – Khaled
    Dec 4, 2018 at 17:15
  • _context.SaveChanges() is called, ef tend to save two copies of the item does the method ItemSubmit called twice? you can debug your app and put a breakpoint on the method to see if its called twice or not.
    – Bagus Tesa
    Dec 5, 2018 at 1:12

1 Answer 1

0

I actually found the solution a while ago but i forgot to post here!

i dont know how to explaing it but when the image is being created it filled the item navigation property with a new item with the same information of the item sent by the form! So i just added these two lines before the uploading image code in the ItemSubmit Controller

imageModel.Item = null;
imageModel.ItemId = item.Id;

i also had a problem in the model that is sent from the view model so i commented the if(ModelState.IsValid)

hope this would help others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.