Click here to Skip to main content
15,889,491 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Saving related data in entity framework is always been a challenge to me specially when I don't have a drop down list or something else to select the primary key data of primary table. So to give you more detail about what my problem, let me show you what i have in my code: I have two models one is called Product and the second one is Review, The Product model class contains all fields for a product plus a navigation property called Review as seen below. Worth to be mention that there is a one to many relation ship set on Product and Reviews table where a Product can have many Reviews.
C#
public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public string ProductDescription { get; set; }
        public decimal ProductPrice { get; set; }
        public string ProductCategory { get; set; }
        public Boolean ProductIsUnlimited { get; set; }
        public Boolean ProductAvailable { get; set; }
        public Boolean DiscountAvailable { get; set; }
        public byte[] MainPicture { get; set; }
        public string MainPictureMimeType { get; set; }
        public byte[] SecondPicture { get; set; }
        public string SecondPictureMimeType { get; set; }
        public byte[] ThirdPicture { get; set; }
        public string ThirdPictureMimeType { get; set; }

        [HiddenInput(DisplayValue=false)]
        public virtual ICollection<Review> Reviews { get; set; }
    }

And the Review model contains all the fields required for a review as seen below.
C#
public class Review
    {
        [HiddenInput(DisplayValue=false)]
        public int ReviewId { get; set; }
        [Required]
        public int ProductID { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Subject { get; set; }
        [Required]
        public string Body { get; set; }
    }

I have controller called ProductController and on that controller i defined a ViewResult method to fetch a Product from database and then all the reviews which is related to that product of course using Review navigation property which is on Product Model. Here the method ProductDetails
C#
public ViewResult ProductDetails(int productId)
        {
            Product product = repository.Products
               .Include(p => p.Reviews)
                .FirstOrDefault(p => p.ProductID == productId);
            return View(product);
        }

So that i have a view for above method where it display product details and reviews, the reviews placed in a partial view and i called in ProductDetails main view. Then i have a another partial view by the name _CreateReview where a form resides in this partial with some script for creating a new review as seen here.
@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.ProductID)
    @Html.EditorFor(m => m.Name)
    @Html.EditorFor(m => m.Subject)
    @Html.TextAreaFor(m => m.Body)
    <input id="Submit" type="submit" value="Submit" />
}

    <script>
        var url = '@Url.Action("CreateReview", "Product")';
        var reviews = $('#reviews');
        var form = $('form');
        $('#Submit').click(function () {
            $.post(url, form.serialize(), function (response) {
                if (response) {
                    reviews.append($('#col-sm-12').val()); // add the new Review to the existing reviews
                    form.get(0).reset(); // reset the form controls
                }
            }).fail(function (result) {
                // oops
            });
            return false; // cancel the default submit
        });
    </script>

As you can see in above script I post the data to controller CreateReview action to save the review. Here is CreateReview JsonResult method.
C#
[HttpPost]
       public JsonResult CreateReview (Review review)
       {
           Review dbEntry = db.Reviews.Find(review.ReviewId);
               if (dbEntry != null)
               {
                   dbEntry.ProductID = review.ProductID;
                   dbEntry.Name = review.Name;
                   dbEntry.Subject = review.Subject;
                   dbEntry.Body = review.Body;
               }

           db.SaveChanges();
           return Json(true);
       }

The problem starts from there, everything seems to work just fine the only piece of puzzle missing is that i couldn't figure out how to get the ProductID of that Product which is fetched by the ProductDetails view method and pass it to my CreateReview JsonResult to create a new review. Any help would be much appreciated, Thanks in advance.

Too long question just to get an ID, Ain't it? Sorry guys I am new to programming.

What I have tried:

[HttpPost]
public JsonResult CreateReview (Review review)
{
Review dbEntry = db.Reviews.Find(review.ReviewId);
if (dbEntry != null)
{
dbEntry.ProductID = review.ProductID;
dbEntry.Name = review.Name;
dbEntry.Subject = review.Subject;
dbEntry.Body = review.Body;
}

db.SaveChanges();
return Json(true);
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900