Sam
Sam

Reputation: 35

I am not able to implement the edit code in asp.net mvc

I am very new on starting a asp.net mvc project on my own. I am done with create work but i am stucked on edit work

This is my DAL Code

public class DonationContext:DbContext
{
    public DbSet<DonorModel> DonorModel { get; set; }
}

This is my controller code

private DonationContext dc = new DonationContext();
public ActionResult Edit()
{
    return View();
}

[HttpPost]
public ActionResult Edit(int id)
{
    if (ModelState.IsValid)
    {
        dc.DonorModel.Add(donorModel);
        dc.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(donorModel);
}

Upvotes: 0

Views: 39

Answers (2)

MVC
MVC

Reputation: 679

You can use your [HttpPost] Edit like this below code. Currently, you are adding the data into database. So, to update the record, you need to either use Attach or EntityStates.

[HttpPost]
public ActionResult Edit(DonorModel donorModel)
{
    if (ModelState.IsValid)
    {
        dc.Entry(donorModel).State = System.Data.Entity.EntityState.Modified;
        dc.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(donorModel);
}

Upvotes: 0

Xariez
Xariez

Reputation: 789

You might need to either attach it or set EntityStates for it to work. I've also seen some cases where you need to turn off EntityFramework's Validation, but you'd probably notice if that's the case.

Generally, as long as your DbContext is working as intended (if you're unsure, set up a debugger and go through it right now), what you got should work, but it's worth a shot.

Upvotes: 1

Related Questions