2014-02-26 4 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" /> 

내가 클릭 더 버튼을 추가해야

의 목록을 가지고 MVC 컨트롤러에 serviceslist을 전송하고자합니다. 기본적으로 배열로 목록을 보낼 필요가 있다고 생각합니다. 내가 어떻게 해?

$('#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으로 변경해야합니다. 이 같은 submit로 버튼을 만들어 할 수있는 대안으로

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

,

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