2012-02-24 70 views
0

我正在努力向我的MVC 3 EF模型的第一個項目添加一個編輯功能,有一個列表,並且用戶可以編輯一行QuestionsMVC;錯誤消息在我的控制器HTTPOST動作編輯

我的實體QuestionsCoreVaue和SubjectType,CoreValueSubjectType有多對多的關係Question

注意:不要讓CreateViewModel的名稱混淆你,我在創建和刪除視圖上使用它。 :)

這是我Controller在我的GET操作:

public ActionResult Edit(int id) 
{ 
    Question q = Arep.GetQuestionById(id); 
    CreateViewModel model = new CreateViewModel(); 
    List<SubjectType> subjectypes = Arep.getallS(); 
    List<CoreValue> corevalues = Arep.getallC(); 
    model.SubjectTypes = new SelectList(subjectypes, "SID", "Sname"); 
    model.CoreValues = new SelectList(corevalues, "CID", "Cname"); 

    return View(model); 
} 

這是我裏面的方法我AdminRepository

public Question GetQuestionById(int id) 
    { 
    return db.Question.SingleOrDefault(m => m.QID == id); 
    } 

    public void changequestion(Question question) 
    { 
     db.ObjectStateManager.ChangeObjectState(question, EntityState.Modified); 
    } 

    public List<SubjectType> getallS() 
    { 
     var Allsubjectypes = from SID in db.SubjectType 
          select SID; 
     return Allsubjectypes.ToList(); 
    } 

    public List<CoreValue> getallC() 
    { 
     var AllCorevalues = from CID in db.CoreValue 
          select CID; 
     return AllCorevalues.ToList(); 
    } 

這是在我的POST操作我Controller

[HttpPost, ActionName("Edit")] 
public ActionResult EditConfirmed(CreateViewModel model) 
{ 
    Question question = new Question(); 
    //question.QID = id;//test 
    if (ModelState.IsValid) 
    { 
     Arep.changequestion(question); 
     Arep.save(); 
     return RedirectToAction("Edit"); 
    } 
    var CoreValueID = int.Parse(model.Cname); 
    var SubjectTypeID = int.Parse(model.Sname); 
    var getallC = Arep.getbycid(CoreValueID); 
    var getallS = Arep.getbysid(SubjectTypeID); 



    return View(model); 
} 

這是我的CreateViwModel:

public string QuestionText { get; set; } 
public string Cname { get; set; } 
public string Sname { get; set; } 

public SelectList SubjectTypes { get; set; } 
public SelectList CoreValues { get; set; } 

這是basicly我編輯的代碼和我得到這個eror當我嘗試更改值並提交:

Current Object State Manager contains no Object Stat Entry that references an object of type NKI3.Models.Question. 

我不知道什麼casuses這個錯誤? :S

在此先感謝!

回答

1

在EditConfirmed中,我認爲你想得到一個存在的問題,而不是創建一個新的問題。新的問題不會被ObjectContext跟蹤。

[HttpPost, ActionName("Edit")] 
public ActionResult EditConfirmed(CreateViewModel model) 
{ 
    Question question = new Question(); // I think you want to get a existing question here 
    //question.QID = id;//test 
    if (ModelState.IsValid) 
    { 
     Arep.changequestion(question); 
     Arep.save(); 
     return RedirectToAction("Edit"); 
    } 
    var CoreValueID = int.Parse(model.Cname); 
    var SubjectTypeID = int.Parse(model.Sname); 
    var getallC = Arep.getbycid(CoreValueID); 
    var getallS = Arep.getbysid(SubjectTypeID); 



    return View(model); 
}