0

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

当用户在 my 中输入一个值,DDL然后TextArea单击我的表单按钮时,它基本上会执行一个 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);
    }

Comment并且Grade也可以为空。

实体的关联如下

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

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

提前致谢!

4

1 回答 1

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);
            }
        }
于 2012-04-25T17:47:34.690 回答