Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Updating a database FK with another tables PK

$
0
0

HI guys

I have two related tables. (1) Departments and (2) Sub departments with PK and FK relationships. 

I have a view with a dropdown list of DepartmentsID which updates the database Sub_Departments (or categories), However I get this error.

What am I doing wrong ?thanks

Here is the error message 

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Admin.i_EF.Classes.Departments', but this ViewDataDictionary instance requires a model item of type 'Admin.i_EF.Classes.Departments_Category'.

My classes

namespace Admin.i_EF.Classes
{
    public class Departments_Category
    {
        [Key]
        public int CategoryID { get; set; }              // This is the PK

      //  [ForeignKey("DepartmentID")]
        public int DepartmentID  { get; set; } // this is a FK
        public Departments Departments { get; set;}



// Main class is 


namespace Admin.i_EF.Classes
{
    public class Departments
    {
        [Key]
        public int DepartmentID { get; set; }
	//[Display(Name ="Department_Name")]
	[Required]
        [StringLength(150, ErrorMessage = "First name cannot be longer than 150 characters.")]
        public string Department_Name { get; set; }



// and my view is

 <select asp-for="DepartmentID" class="form-control" asp-items="@(new SelectList(@ViewBag.depts,"DepartmentID","Department_Name"))"></select>


//finally my controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Categories_Create([Bind("DepartmentID,Product_Name")] Departments Departments_Category)
        {
            if (ModelState.IsValid)
            {
                _context.Add(Departments_Category);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(Departments_Category);
        }


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>