Controller Action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult New_Shelf(Shelf shelf)
{
shelf.User_Id = int.Parse(Request.Cookies["UserId"].Value);
db_shelf.Shelves.Add(shelf);
db_shelf.SaveChanges();
return RedirectToAction("Index", "Home");
}
Model:
namespace Book_shelf.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class Shelf
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public int Size { get; set; }
[ForeignKey("Id")]
public int User_Id { get; set; }
}
}
View:
@model Book_shelf.Models.Shelf
@using (Html.BeginForm("New_Shelf", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<label style="font-family:sans-serif">Name</label>
<br />
@Html.TextBoxFor(a => a.Name)
<br />
<br />
<label style="font-family:sans-serif">Size</label>
<br />
@Html.TextBoxFor(a => a.Size)
<br />
<br />
<button class="btn btn-sm" type="submit"> Add</button>
}
Error:
Cannot insert explicit value for identity column in table 'Shelf' when >IDENTITY_INSERT is set to OFF.
I am new to ASP.net MVC and Entity Framework. I am trying to Insert a new row for my table 'Shelf'.But it looks like that the view is sending Id as well when posting data to Action.I Tried to Log the value of shelf.Id in the action and it was '0'.How do i prevent the view to send any data in for Id property?