Click here to Skip to main content
15,946,663 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...

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" })
Share this answer

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