asp.net mvc jquery发布多个隐藏字段

时间:2014-02-26 11:15:02

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

我有这个隐藏字段列表

   <input type="hidden" value="1" id="serviceslist" name="serviceslist" />
   <input type="hidden" value="2" id="serviceslist" name="serviceslist" />
   <input type="hidden" value="3" id="serviceslist" name="serviceslist" />

我添加了更多按钮,当点击时想要将服务列表发送到mvc控制器。基本上我认为我需要将列表作为数组发送。我怎么能这样做?

  $('#addmoreservices').click(function () {          
     var serviceslist= $("#serviceslist").val()
        $.ajax({
            url: url,
            data: { serviceslist: serviceslist },
            cache: false,
            dataType: "json",
            traditional: true,
            type: "POST",
            success: function (data) {

                alert("dddd");
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
    });

这是我的mvc控制器

 [HttpPost]
    public ActionResult AddmoreServices(List<int> serviceslist)
    {

        return View();
    }

3 个答案:

答案 0 :(得分:3)

你的html和js中有一些错误。

首先,id必须是唯一的:

<input type="hidden" value="1" id="val1" />
<input type="hidden" value="2" id="val2" />
<input type="hidden" value="3" id="val3" />

第二个,jquery val()函数获取匹配元素集中第一个元素的当前值,而不是数组。

第三个是关于在服务器上发布您的数据。默认情况下jquery.ajax在您的网址contentType='application/x-www-form-urlencoded'中发布您的数据,应将其更改为application/json

serviceslist = [$("#val1").val(), $("#val2").val() ,$("#val3").val()];
$.ajax({
   url: url,
   data: serviceslist,
   contentType: 'application/json',
   ....

答案 1 :(得分:1)

或者,您可以将按钮设为submit,例如

@using(Html.BeginForm("AddMoreServices", "Your controller name", FormMethod.Post, null)) {

<input type="hidden" value="1" id="val1" name="serviceslist" />
<input type="hidden" value="2" id="val2" name="serviceslist" />
<input type="hidden" value="3" id="val3" name="serviceslist" />

<button type="submit" value="Add More Services"/>

}

并且您的控制器操作方法可以是

[HttpPost]
public ActionResult AddMoreServices(FormCollection collection)
{
    try
    {
        string[] test = collection.GetValues("serviceslist");

        // here test[0] will give you the value of `val1`
        // test[1] will give `val2` and test[2] will give `val3`'s values
    }
    catch (Exception ex)
    {
        return null;
    }
}

答案 2 :(得分:0)

尝试这样的事情,

HTML:

<input type="hidden" value="1" class="serviceslist" name="serviceslist" />
<input type="hidden" value="2" class="serviceslist" name="serviceslist" />
<input type="hidden" value="3" class="serviceslist" name="serviceslist" />

JQUERY:

$('#addmoreservices').click(function () {          
    var serviceslist= $(".serviceslist").serialize();
    $.ajax({
        url: url,
        data: serviceslist,
        cache: false,
        dataType: "json",
        traditional: true,
        type: "POST",
        success: function (data) {

            alert("dddd");
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });
});