0

I am using MVC3 and classes generetad from EntityFranmework for saving some data into a Database.

The controller

// Get
public ActionResult Create(Guid StudentID)
{
    Semester semester = new Semester();

    ViewBag.BranchID = new SelectList(db.Branches, "ID", "Name");
    semester.Student = db.Students.Single(s => s.ID == StudentID);

    return PartialView(semester);
} 

//
// POST: /Semester/Create

[HttpPost]
public ActionResult Create(Semester semester)
{
    semester.ID = Guid.NewGuid();
    semester.CreatedDate = DateTime.Now;
    semester.CreatedBy = "ddf";


    db.Semesters.AddObject(semester);
    db.SaveChanges();
    return RedirectToAction("Index", "Student");      
}

I do get all the result of the student at get Method but all the student data are Lost at the post method.

Help!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Burim
  • 1
  • 1
  • 1
    Do you mean that the Semester object passed to the Post method is null or has empty values? If so, I suspect it could be a binding problem, in which case could you share your View HTML? – Lee D Jun 18 '11 at 08:05

1 Answers1

2

The object passed to POST action is not the same as object passed to the view in GET action. In your POST action you get Semester instance created by MVC using only parameters Request (query string, post data) - that means Student instance is long gone. You will need to pass student ID to POST action and fill it there.

[HttpPost]
public ActionResult Create(Guid studentID, Semester semester)
{
    semester.ID = Guid.NewGuid();
    semester.CreatedDate = DateTime.Now;
    semester.CreatedBy = "ddf";

    semester.Student = db.Students.Single(s => s.ID == StudentID);

    db.Semesters.AddObject(semester);
    db.SaveChanges();
    return RedirectToAction("Index", "Student");      
}
Lukáš Novotný
  • 9,012
  • 3
  • 38
  • 46