Click here to Skip to main content
14,976,940 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone...
just like all others i am also here to discuss my code problem...
I am new to MVC and i want to insert data from multiple partial views but i am facing a problem. I have populated the dropdownlist from "Category" model and i have one more model which is "Product" Model. all input fields except dropdownlist are razor by using Product Model but the dropdownlist is razor by using Category Model.Remember! I am using ADO.NET in this project not EntityFramework.I have a relational database at back end which contains the product and category relation. Everything works fine but when i click on submit button i want to insert the ID of the selected item in Dropdownlist but i face an error
which is...

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Products_Catagories". The conflict occurred in database "MVC-DB", table "dbo.Catagories", column 'Cat_ID'.

What I have tried:

Here what i am trying..
Function In Database to insert data
public void CreateProducts(Products product)
       CategoryAdminPanel cat = new CategoryAdminPanel();
       string query = "Insert into Products (P_Name,P_Image,P_Price,P_CatagoryID) Values (@name,@image,@price,@category)";
       SqlConnection con = new SqlConnection(con_string);
       SqlCommand cmd = new SqlCommand(query,con);
       cmd.Parameters.AddWithValue("@image", product.P_Image);
       cmd.Parameters.AddWithValue("@category", cat.Cat_ID);

My Controller..
       public ActionResult CreateProductsByAjaxCall(Products product)
           if (ModelState.IsValid)
           return RedirectToAction("Index");

My Product Model
public class Products
    public int P_ID { get; set; }
    public string P_Name { get; set; }
    public string P_Image { get; set; }
    public int P_Price { get; set; }
    public int P_CatedoryID { get; set; }

My Catagory Model..

public class CategoryAdminPanel
        public int Cat_ID { get; set; }
        public string Cat_Name { get; set; }
Updated 15-Mar-17 20:47pm
sachin.vishwa90 10-Mar-17 0:37am
you need to check what is value in the cat.Cat_ID when your model is posted. i suspect that the value in cat.Cat_ID is not there is your dbo.Catagories table. thats why you are getting this error.
if that is the case then your model is not posting proper value from view. That is the problem here.
for more clarity post your view's code as well
Muhammd Aamir 10-Mar-17 0:56am
@sachin.vishwa90 the value in the cat_ID is Zero "0" when i use break point on this function... now here is my view as well.

@model WebApplication.Models.Products

Create Products

@using (Html.BeginForm())

@Html.ValidationSummary(true, "", new { @class="text-danger"})

@Html.LabelFor(model => model.P_Name, "Product Name:", htmlAttributes: new { @class="control-label col-md-2"})

@Html.EditorFor(model => model.P_Name, new { htmlattributes = new { @class="form-control"} })
@Html.ValidationMessageFor(model => model.P_Name, "", new { @class="text-danger"})

@Html.LabelFor(model => model.P_Image, "Upload Image:", htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.P_Image, new { htmlattributes = new { @class = "form-control" ,type="file"} })
@Html.ValidationMessageFor(model => model.P_Image, "", new { @class = "text-danger" })

@Html.LabelFor(model => model.P_Price, "Product Unit Price:", htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.P_Price, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.P_Price, "", new { @class = "text-danger" })

@Html.LabelFor(model => model.P_CatedoryID, "Product Category:", htmlAttributes: new { @class = "control-label col-md-2" })

@* Here i call my partial view that populates the dropdown list *@

Button Here ..
Muhammd Aamir 10-Mar-17 1:02am
Here is my Partial View Code..

@model WebApplication.Models.CategoryAdminPanel

@Html.DropDownList("Categories", (SelectList)ViewBag.RequiredKey, new { @class = "form-control" })
sachin.vishwa90 10-Mar-17 1:06am
you know you can debug the view as well. now you need to observe what is the value in your model.P_CategoryID, because the same value will be posted from your view. And one more thing you will observe in your code while inserting value in your table you are using following,
CategoryAdminPanel cat = new CategoryAdminPanel(); //create new object
cmd.Parameters.AddWithValue("@category", cat.Cat_ID); // putting value from cat object, since it doesnot have any value with it.

where as you should be picking categoryId from your product model as product.P_CatedoryID;
check if that works.
Muhammd Aamir 10-Mar-17 1:25am
absolutely you are getting closer in finding my problem.. i tried this right now but the problem is again same. the value in product.P_CategoryID is Zero "0". i appreciate your knowledge now the come to pint which is i populate my dropdownlist from category model how can get CatID when i click on submit button when i used this "CategoryAdminPanel cat = new CategoryAdminPanel()" you are right it will create a new object but how can i get CatID if i am not using this...
Muhammd Aamir 10-Mar-17 1:29am
The dropdownlist populate from CategoryAdminPanel model not from Products. so product did not have any definition of this
sachin.vishwa90 14-Mar-17 1:53am
you can keep it very simple by having viewModel, which will consist of all the property needed in your view, this will also include the properties which you want on your post back.
check below link it will definitely help you
j snooze 10-Mar-17 17:40pm
I don't know if this helps, but from my newbie MVC days I gradually started using viewmodels instead of models themselves inside my views. I created view model objects that encapsulated all the properties I would need. For instance your product model. Looks good. If you had a product view model called public class ProductViewModel which had all your product properties plus add these 2 additional properties.
public int Cat_id {get;set;}
public virtual List<categoryadminpanel> Categories{ get; set; }

Add this to your view...
@Html.DropDownListFor(model => model.Cat_Id, new SelectList(Model.Categories, "Cat_ID", "Cat_Name"), "Category", new { @class = "form-control", @id = "[your drop down list name id]" })

So before you show the view obviously instead of filling your viewbag with the List<> you set your product model's Categories to the list of categories. When someone selects one and submits your models Cat_id property will be filled in. Hope this helps. (You shouldn't need a partial view for a drop there a reason why its in its own partial view?)
sachin.vishwa90 14-Mar-17 1:50am
hey chap, this is one of the solution which would definitely help him.
Prateek Dalbehera 15-Mar-17 3:54am
try to debug and verify what values are coming in the runtime, please check in your db code by inserting the same data , by directly running INsert statement in sql server. If its not inserting than there is problem with FK else check your C# code to verify what value its sending to database
Muhammd Aamir 15-Mar-17 6:21am
@Prateek Dalbehera the value in Cat_ID is '0' Zero when i debug my code ... and i have face this error
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Products_Catagories". The conflict occurred in database "MVC-DB", table "dbo.Catagories", column 'Cat_ID'.
what i will have to do to resolve this issue..
Prateek Dalbehera 15-Mar-17 7:09am
it seems that problem is with your db part not in code. Have you tried inserting the same value directly through ssms. Please try to insert in sql server and revert back.
Muhammd Aamir 16-Mar-17 1:40am
i have inserted into db but it works fine there is no issue with db so far..
Prateek Dalbehera 16-Mar-17 2:20am
Please cross verify the Cat_ID value in debug mode. It seems that from application the value which you are trying to insert is violating the foreign key constraint. Also, while inserting to db directly , have you used '0' as CAt_ID??
Muhammd Aamir 16-Mar-17 2:26am
@Prateek Dalbehera THANK YOU for sharing your knowledge someone find my solution recently now my code works well thankx again
Muhammd Aamir 16-Mar-17 2:33am
@Prateek Dalbehera thank you very much for sharing your knowledge and spent some valuable time while paying attention to my problem.. someone on code project have recently found my solution and now my code works well thankx again
Prateek Dalbehera 16-Mar-17 2:35am
Ok, then please share the problem & solution as well so that it may help others. Thank you.
Muhammd Aamir 16-Mar-17 3:24am
Check my solution if you found any problem in it then please do let me... so i can briefly describe you

1 solution

I have found the solution to this problem.. the problem is when i pass the viewbage value to my partial view it works fine but when i select the ddl value and trying to submit into database it does not recognize which value of ddl is selected so i need to use "P_CategoryID" as DDL id which is my "product" class property instead of viewbag reserve keyword "Category"

here is my controller that populate the DDL:

public ActionResult CreateProductsByAjaxCall()
         ViewBag.P_CatedoryID = new SelectList(db.GetALLCategoriesForProducts(), "Cat_ID", "Cat_Name");
         //ViewBag.Categories = db.GetALLCategoriesForProducts().Select(x => new SelectListItem { Text = x.Cat_Name, Value = x.Cat_ID.ToString() });
         return PartialView();

by changing the id of dropdown list from "Category" to "P_CatedoryID"
@Html.DropDownList("Category", (SelectList)ViewBag.RequiredKey, new { @class = "form-control" })

Now my view code looks like

@Html.DropDownList("P_CatedoryID", (SelectList)ViewBag.RequiredKey, new { @class = "form-control" })

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