MVC:在相同的[HTTPPOST]动作方法中编辑和创建

时间:2012-04-25 12:12:48

标签: asp.net-mvc asp.net-mvc-3 http-post actioncontroller

我首先在我的项目中使用MVC3-Viewmodel模型。

当用户在我的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]

感谢任何形式的帮助。

提前致谢!

1 个答案:

答案 0 :(得分: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);
            }
        }