2014-02-26 47 views
0

我有隐藏字段asp.net的MVC的jQuery发布多个隐藏字段

<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" /> 

我有添加更多按钮,点击它时,这个名单要发送的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(); 
    } 
+1

'id'应该是唯一的 –

回答

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

或者你可以通过按钮的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; 
    } 
}