如何将空/零值传递给控制器​​以建立密钥

时间:2015-04-28 16:54:26

标签: jquery asp.net asp.net-mvc-5

我正在努力尝试一个" smart"控制器方法,可以检测用户是在发送新问题还是更新数据库中的现有问题。我遇到的问题是我似乎无法告诉ModelState.IsValid方法"此QuestionID为空,因此将其视为新的"否则"更新记录"。当QuestionID的值为0时,我没有得到ModelState.IsValid == true,导致没有任何内容发布到数据库。关键似乎在于QuestionID属性,但我似乎错过了一些明显的东西。任何人都可以帮助我吗?

Flow:jQuery通过AJAX将数据传递给控制器​​,控制器返回响应。

jQuery代码

function questionField() {
            var TopicID = $("#TopicID").val();
            var QuizID = $("#QuizID").val();
            var QuestionID = $("#QuestionID").val();
            var Question = $("#quizQuestion").val();
            var token = $("#quizQuestionsForm > [name=__RequestVerificationToken]").val();
            $("#questionSaveArea").effect("slide", "fast");


            //Start building update string
            var questionData = "__RequestVerificationToken=" + token;

            //Wrote this "backward" because QuestionID != undefined will not work based on how 
            //JS handles objects. The variable already exists, but a backwards check will allow this to pass correctly.
            if (undefined != QuestionID)
            {
                questionData += "&QuestionID=" + QuestionID;
            }
            else
            {
                question += "&QuestionID=";
            }


            //MUFFIN: Add an active question parameter

            questionData += "&Question=" + Question + "&QuizID=" + QuizID + "&TopicID=" + TopicID;


            //Don't accept blanks
            if (Question != "") {
                $.ajax({
                    type: "POST",
                    url: "../../QuizQuestions/PostQuestionData",
                    data: questionData,
                    contentType: "application/x-www-form-urlencoded",


                    success: function (data) {

                        if (data != "Fail")
                        {
                            console.log("Question saved! Question ID is: " + data);

                            $("#QuestionID").val(data);

                            //QuestionID now exists, get existing Answers (sub function enables fields)
                            getPreviousAnswers();


                            //Enable the addAnswer button();
                            addAnswer();

                            $("#questionSaveArea")
                                        .delay('500')
                                        .fadeIn('fast')
                                        .html("<small><em>saved</em></small>");
                        }

                        if (data == "Fail")
                        {
                            alert("Cannot save question! Please try again, or contact support.");
                            $("#questionSaveArea")
                                        .delay('500')
                                        .fadeIn('fast')
                                        .html("<small><em>error</em></small>");
                        }

                    },

                    error: function () {
                        $("#questionSaveArea")
                                    .delay('500')
                                    .fadeIn('fast')
                                    .html("<small><em>unable to save, please try again</em></small>");
                    }
                }); //end AJAX


            }

            if (Question === "") {
                $("#questionSaveArea")
                                .delay('500')
                                .fadeIn('fast')
                                .html("<small><em>cannot save, empty question</em></small>");
            };


        }

控制器代码

// POST: QuizQuestions/PostQuestionData
        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> PostQuestionData([Bind(Include = "QuestionID,Question,TopicID,isValidQuestion,QuizID")] QuizQuestions quizQuestions)
        {
            //If statement to catch new questions
            //Questions will be active by default for new questions
            if(quizQuestions.QuestionID == 0)
            {
                quizQuestions.IsValidQuestion = true;

                if (ModelState.IsValid)
                {

                    db.QuizQuestions.Add(quizQuestions);
                    await db.SaveChangesAsync();
                    return Content(quizQuestions.QuestionID.ToString());
                };

                //The model state is not valid here so a fail flag is sent
                return Content("Fail");

            }

            else
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        db.Entry(quizQuestions).State = EntityState.Modified;
                        await db.SaveChangesAsync();
                        return Content("Success"); 
                    }

                    catch
                    {
                        return Content("No change was detected. Skipping save.");
                    }

                };
                return Content("Fail");

            };
        }

模型

[Table("QuizQuestions")]
    public class QuizQuestions
    {

        [Column("QuestionID")]
        [Key]
        [HiddenInput(DisplayValue = false)]
        public int QuestionID { get; set; }

        [Column("IsValidQuestion")]
        [Display(Name = "question active?")]
        public virtual bool IsValidQuestion { get; set; }


        [Column("Question")]
        [Required(ErrorMessage="question is required to proceed")]
        [Display(Name = "question")]
        [DataType(DataType.MultilineText)]
        public string Question { get; set; }

        [Column("TopicID")]
        [HiddenInput(DisplayValue = false)]
        public int TopicID { get; set; }

        [Column("QuizID")]
        [HiddenInput(DisplayValue = false)]
        public int QuizID { get; set; }

        public virtual ICollection<QuizAnswers> QuizAnswers { get; set;} 

    }

1 个答案:

答案 0 :(得分:0)

我相信你有几个选择:

选项1:将QuestionID更改为可为空的int?在模型中,然后在控制器操作中测试null以创建新问题。

选项2:在JS代码中调用控制器操作将QuestionID设置为一些可测试的值,如QuestionID = -1,然后在控制器中测试-1以创建新问题。

@Zaki - 是正确的,请确保在调用控制器之前在JS中设置QuestionID为correclty且QuestionID = 0。