MVC Homecontroller编辑DB中的详细信息

时间:2012-10-20 00:52:07

标签: asp.net-mvc ckeditor

所以只使用了一个基础教程来创建数据库并向其添加新记录。这一切都很好......但是现在我想编辑一条记录....

// GET: /Home/Edit/5

    public ActionResult Edit(int id)
    {
        return View();
    }

    //
    // POST: /Home/Edit/5

    [HttpPost]
    //public ActionResult Edit(int id, FormCollection collection)
    public ActionResult Edit([Bind(Exclude = "id")]MovieTable1 movieToCreate)
    {
        try
        {
            // TODO: Add update logic here

           //so i need to insert a line of code here to say something like update
            //I was using the previous code:
           //_entities.AddToMovieTable1(movieToCreate);
            _entities.SaveChanges();           

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

这不起作用我认为我所要做的就是编辑'_entities.AddToMovieTable1(movieToCreate);'要编辑记录的东西

获取添加新记录的工作已经使用了代码...

 public class HomeController : Controller
{
    private MoviesDBEntities _entities = new MoviesDBEntities();
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View(_entities.MovieTable1.ToList());
    }

    //
    // GET: /Home/Details/5

    public ActionResult Details(int id)
    {
        return View();
    }

    //
    // GET: /Home/Create

    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Home/Create

    [HttpPost]
    //public ActionResult Create(FormCollection collection)
    public ActionResult Create([Bind(Exclude = "id")]MovieTable1 movieToCreate)
    {
        try
        {
            // TODO: Add insert logic here
            _entities.AddToMovieTable1(movieToCreate);
            _entities.SaveChanges();

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

1 个答案:

答案 0 :(得分:2)

你可以使用:

_entities.Attach(moveiToModify);
_entities.Entry(moveiToModify).State = EntityState.Modified;

我真的不知道,为什么要排除ID属性,这是更新所必需的。