2

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.

2
  • Can you alert your list first, because array index start with 0. Seems everything ok. Commented Jun 26, 2016 at 18:26
  • Simply, change method parameter to string[] values and that's all. Commented Jun 26, 2016 at 20:15

1 Answer 1

9

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); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Right , It has to be typed object in controller. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.