MesutAtasoy
MesutAtasoy

Reputation: 822

How to pass Array to MVC Controller with Jquery?

I am beginner to develope .Net MVC 5 application. But I have some problem with passing array or object to controller with Jquery.

I'm adding dynamically input fields with button. I want to pass input's data to controller. But I couldn't succeed.

Html Section is like that;

        <div id='TextBoxesGroup'>
            <div id="TextBoxDiv1">
             <label>Textbox #1 : </label><input type='text' id='textbox1'>
            </div>
        </div>
        <input type='button' value='Add Button' id='addButton'>
        <input type='button' value='Remove Button' id='removeButton'>
        <input type='button' value='Get TextBox Value' id='getButtonValue'>

Get Value button function is like that;

 $("#getButtonValue").click(function () {
            var list = new Array();
            for (i = 1; i < counter; i++) {
                list[i] = $('#textbox' + i).val();
                alert(list[i]);
            }
            var postData = { values: list };

            $.ajax({
                type: "POST",
                url: "/Surveys/PostQuestionAndOptions",
                data: postData,
                success: function (data) {
                    alert(data);
                },
                dataType: "json",
                traditional: true
            });
        });

Even I set "traditional" by true , the model is null.

[HttpPost]
        public JsonResult PostQuestionAndOptions(string[] model)
        {
            return Json(true);
        }

Could any one help me ? Thank you.

Upvotes: 2

Views: 21524

Answers (1)

Bryan Euton
Bryan Euton

Reputation: 929

You need to have a strongly typed object.

JavaScript

$("#getButtonValue").click(function (e) {
    e.preventDefault();
    var list = []; 
    for (var i = 1; i < counter; i++) { 
        list.push($('#textbox' + i).val());
    } 
    var postData = { values: list }; 
    $.ajax({ 
        type: "POST", 
        url: "/Surveys/PostQuestionAndOptions", 
        data: postData, 
        success: function (data) { 
            alert(data); 
        }, 
        dataType: "json", 
        traditional: true 
    }); 
});

Strongly typed object

public MyValues {
    public list<string> values {get; set;}
}

Controller method

[HttpPost] 
public JsonResult PostQuestionAndOptions(MyValues model) { 
    return Json(true, JsonRequestBehavior.AllowGet); 
}

Upvotes: 9

Related Questions