2014-02-26 52 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; 
    } 
}