Burim
Burim

Reputation: 1

Values on PostBack getting lost

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!

Upvotes: 0

Views: 1757

Answers (1)

Lukáš Novotný
Lukáš Novotný

Reputation: 9052

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");      
}

Upvotes: 2

Related Questions