2012-04-25 37 views
0

我在我的项目中首先使用MVC3-Viewmodel模型。MVC:编辑和创建相同的[HTTPOST]操作方法

当用户在我的DDLTextArea中输入一个值,然后单击我的表单按钮时,它会基本执行一个ajax url.post到我的POST动作,现在我的Post Action方法创建并保存它。但我要的是某种类型的检查,例如:

  • 第1步:如果SelectQuestion有任何答案
  • 第2步:如果答案存在做一个更新
  • 3步:如果答案不存在创建一个新的并保存它。

这是我的控制器看起来像现在:

[HttpPost] 
    public JsonResult AnswerForm(int id, SelectedQuestionViewModel model) 
    { 
     bool result = false; 
     var goalCardQuestionAnswer = new GoalCardQuestionAnswer(); // Creates an instance of the entity that I want to fill with data 

     SelectedQuestion SelectedQ = answerNKIRepository.GetSelectedQuestionByID(model.QuestionID); // Retrieve SelectedQuestion from my repository with my QuestionID.    
     goalCardQuestionAnswer.SelectedQuestion = SelectedQ; // Filling my entity with SelectedQ 
     goalCardQuestionAnswer.SelectedQuestion.Id = model.QuestionID; // filling my foreign key with the QuestionID 
     goalCardQuestionAnswer.Comment = model.Comment; // Filling my entity attribute with data 
     goalCardQuestionAnswer.Grade = model.Grade; // Filling my entity attribute with data 
     answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer); // adding my object 
     answerNKIRepository.Save(); // saving 
     result = true; 
     return Json(result); 
    } 

CommentGrade可为空以及。

该实体是像

[Question](1)------(*)[SelectedQuestion](1)-----(0..1)[GoalCardQuestionAnswer] 

任何形式的帮助表示赞赏有关。

在此先感谢!

回答

0

我实现了我的问题,答案是以下几点:

[HttpPost] 
     public JsonResult AnswerForm(int id, SelectedQuestionViewModel model) 
     { 
      SelectedQuestion SelectedQ = answerNKIRepository.GetSelectedQuestionByID(model.QuestionID); 

      if (SelectedQ.GoalCardQuestionAnswer == null) 
      { 

       var goalCardQuestionAnswer = new GoalCardQuestionAnswer(); 
       goalCardQuestionAnswer.SelectedQuestion = SelectedQ; 
       goalCardQuestionAnswer.SelectedQuestion.Id = model.QuestionID; 
       goalCardQuestionAnswer.Comment = model.Comment; 
       goalCardQuestionAnswer.Grade = model.Grade; 
       this.answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer); 
       this.answerNKIRepository.Save(); 
       const bool Result = true; 
       return this.Json(Result); 
      } 
      else 
      { 
       if (SelectedQ.GoalCardQuestionAnswer != null) 
       { 
        SelectedQ.GoalCardQuestionAnswer.Comment = model.Comment; 
       } 

       if (SelectedQ.GoalCardQuestionAnswer != null) 
       { 
        SelectedQ.GoalCardQuestionAnswer.Grade = model.Grade; 
       } 
       const bool Result = false; 
       return this.Json(Result); 
      } 
     } 
相关问题