There are already a normal scaffolding for CRUD in Asp.net MVC but i am using my own code for saving the post.
Abstract.cs(Model)
public class Abstract { public int ID { get; set; } [Required] public ApplicationUser Member { get; set; } [Required] public string AbstractTitle { get; set; } [Required] public string AbstractAim { get; set; } [Required] [StringLength(300)] public string AbstractDetails { get; set; } [Required] public string Author { get; set; } public string CoAuthor { get; set; } } AbstractController.cs
public class AbstractsController : Controller { private readonly ApplicationDbContext _context; public AbstractsController() { _context = new ApplicationDbContext(); } [Authorize] public ActionResult Create() { return View(); } [Authorize] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(AbstractFormViewModel viewModel) { if (!ModelState.IsValid) return View("Create", viewModel); var memberId = User.Identity.GetUserId(); var member = _context.Users.Single(u => u.Id == memberId); var abs = new Abstract { Member = member, AbstractTitle = viewModel.AbstractTitle, AbstractAim = viewModel.AbstractAim, AbstractDetails = viewModel.AbstractDetails, Author = viewModel.Author, CoAuthor = viewModel.CoAuthor }; _context.Abstracts.Add(abs); _context.SaveChanges(); return RedirectToAction("Index", "Home"); } } This is my controller and model. Here i am trying to implement my own way to perform edit and update stuffs. Here i am really confused how to perform edit stuffs for this create action.
public ActionResult Edit(int id) { var customer = _context.Abstracts.SingleOrDefault(c => c.Id == id); if (customer == null) return HttpNotFound(); var memberId = User.Identity.GetUserId(); var member = _context.Users.Single(u => u.Id == memberId); var viewModel = new Abstract { Member = member, AbstractTitle = viewModel.AbstractTitle, AbstractAim = viewModel.AbstractAim, AbstractDetails = viewModel.AbstractDetails, Author = viewModel.Author, CoAuthor = viewModel.CoAuthor }; return View("CustomerForm", viewModel); } But this isn't working please suggest or provide me a solution to write a edit action.
AbstractFormViewModelfor yourEdit()method?db.Entry(Abstract).is a typo and is reallydb.Entry(abstract).- ditto inreturn Viewin both methods.db.Entry(Abstract).State = EntityState.Modifiedpossibly throwing error during entity modification. You can useAbstractFormViewModelinEditmethod to fillAbstractmodel before usingEntityState.Modified.AbstractFormViewModel()and set its properties based on the data model and pass that view model to the view (its just the opposite if what you do in theCreatePOST method