2011-01-24 4 views
5

Asp.Net MVC 응용 프로그램에서 작업 할 때 응용 프로그램에서 양식을 제출하기 위해 jQuery.POST 메서드를 사용하고 있습니다.jQuery.POST - Form.Serialize()로 다른 매개 변수 전달 - Asp.net MVC 3

예컨대 위의 코드에서

jQuery.post('/Product/Save', jQuery(document.forms[0]).serialize(), 
     function (data) { alert('Product Added Successfully.); } 
); 

, 나는 .. 다른 매개 변수를 전달 ..의 말 ProductID을 수 있도록합니다.

그래서, 아이디어, 난 jQuery.POST method 모두 jQuery(document.forms[0]).serialize()ProductID variable을 전달하려는, 그래서 난 내 controller's action method 모두 Form and ProductID를 얻을 수 있습니다.

아무도 내가 이것을 할 수 있다고 알려주시겠습니까?

미리 감사드립니다.

답변

13

당신은 JSON 객체로 양식을 직렬화 할 following plugin를 사용하고 다른 매개 변수를 추가 할 수 있습니다 같은

$.fn.serializeObject = function() 
{ 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function() { 
     if (o[this.name]) { 
      if (!o[this.name].push) { 
       o[this.name] = [o[this.name]]; 
      } 
      o[this.name].push(this.value || ''); 
     } else { 
      o[this.name] = this.value || ''; 
     } 
    }); 
    return o; 
}; 

:

var data = $('form').serializeObject(); 
data['ProductId'] = '123'; 
$.post('<%= Url.Action("Save", "Product") %>', data, function (data) { 
    alert('Product Added Successfully.'); 
}); 
0

Url.Action 메서드를 사용하여 호출 URL을 작성하는 방법은 무엇입니까? 필요에 따라 추가 데이터를 포함 할 수 있습니다.

<%: Url.Action('Save', 'Product', new { "ProductID", your product id }) %> 

이것은 jQuery.post 메서드 호출의 하드 코딩 된 URL을 대체합니다.

0

방법에 대해 :

var url = '<%= Html.BuildUrlFromExpression<MyController>(c => c.Save(":productId")) %>'; 

을 당신 나중에 URL을 게시물 URL의 실제 값으로 바꿀 수 있습니다.

url.replace(':productId', $productId);