如何使用Jquery将Array传递给MVC Controller? [英] How to pass Array to MVC Controller with Jquery?

查看:71
本文介绍了如何使用Jquery将Array传递给MVC Controller?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者,开发.Net MVC 5应用程序。但是我在使用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就是这样;

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
            });
        });

即使我将传统设置为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.

推荐答案

你需要一个强类型的对象。

You need to have a strongly typed object.

JavaScript

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 
    }); 
});

强类型对象

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

控制器方法

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

这篇关于如何使用Jquery将Array传递给MVC Controller?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆