简体   繁体   中英

Unable to pass JSON Data to MVC Controller using AJAX?

In my QUIZ application, I want to send an array of objects (in which one question with four answers & one correct answer as a property of an object) to MVC Controller but it sends null value. The key point to solve this issue was to stringify the JSON object, define a model and get the parameter as the defined model. Is there any Alternative Solution for this?

My View UI Look like this

//VIEW Script

<script>
    $(document).ready(function () {
        $("#btnsubmit").click(function () {
            createquestions();
        });
        function createquestions()
        {
            var things = [];
            var nofques = $("#ddlnofquestions").val();//Coming from Dropdown Value
            for (var i = 1; i <= nofques; i++) {
                var obj = {
                    id: i,
                    question:  CKEDITOR.instances[i.toString()].getData(),
                    answer1:$("#" + i + 1).val(),
                    answer2: $("#" + i + 2).val(),
                    answer3: $("#" + i + 3).val(),
                    answer4: $("#" + i + 4).val(),
                    correctanswer: $("#" + i + 5).val(),                  
                };                
                things.push(obj);               
            }
            var thingss = JSON.stringify({ "things": things });
            $.ajax({    
                type: 'POST',
                url:'Question/CreateQuestion',
                async:true,
                dataType: 'json',
                contentType: "application/json; charset=utf-8", 
                data: { things: JSON.stringify(things) },
                traditonal: true,
                success: function (data) {
                    alert("Sucessfully Created");
                },
          });
        }
    });
</script>

C#: Model Class

public class CreateQuestion
{
    public int id { get; set; }
    public string question { get; set; }
    public string answer1 { get; set; }
    public string answer2 { get; set; }
    public string answer3 { get; set; }
    public string answer4 { get; set; }
    public string correctanswer { get; set; }
}

C#: Controller

public ActionResult CreateQuestion(List<CreateQuestion> things)
{
    //where we try to get an array of objects
    //Working Code......
    return View();    
}

Try changing this on your AJAX call:

data: { things: JSON.stringify(things) },

For this:

data: JSON.stringify(things),

What I think is happening is that the action is expecting a list of objects, but on the AJAX call, you are sending an object that contains an array of objects.

You may try do something like:

[HttpPost] public JsonResult CreateQuestion( POCOthings)

Where POCOthings is an POCO objet suitable to be transformed by mvc model binder. For your case you list of CreateQuestions should be a field of said object. Hope it helps.

Few things to check.

  1. is it 404 error? httppost attribute missing for action.
  2. is JSON.stringify(things) a valid object?
  3. can you try removing dataType? you are returning view but the data type it is expecting is json.

dataType: 'json',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM