2012-05-29 42 views

Trả lời

37
$.post("Yourcontroller/YourAction", { FirstName : $("#txtFirstName").val(), LastName : $("#txtLastName") } ,function(data){ 
    //do whatever with the response 

}); 

bạn tên ViewModel tài sản và Parameter chúng tôi đang đi qua nên giống nhau. Ví dụ: mô hình quan điểm của bạn nên có 2 thuộc tính gọi là FirstNameLastName như mình

public class PersonViewModel 
{ 
    public string FirstName { set;get;} 
    public string LastName { set;get;} 
    // other properties 

} 

Và phương pháp action Gửi nên chấp nhận một tham số kiểu PersonViewModel

[HttpPost] 
public ActionResult YourAction(PersonViewModel model) 
{ 
    //Now check model.FirstName 
} 

Ngoài ra, Nếu xem bạn đang gõ mạnh lên PersonViewModel, bạn có thể chỉ cần gửi biểu mẫu được tuần tự hóa đến phương thức hành động bằng cách sử dụng phương thức jQuery serialize

$.post("Yourcontroller/YourAction", $("#formId").serialize() ,function(data){ 
    //do whatever with the response 

}); 

CHỈNH SỬA: Theo nhận xét

Serialize cũng sẽ quản lý thuộc tính con. Giả sử bạn có một lớp gọi là nghề như thế này

public class Profession 
{ 
    public string ProfessionName { set; get; } 
} 

Và PersonViewModel của bạn có một loại tài sản của Profession

public class PersonViewModel 
{ 
    //other properties 
    public Profession Profession { set; get; } 
    public PersonViewModel() 
    { 
     if (Profession == null) 
      Profession = new Profession(); 
    } 
} 

Bạn sẽ nhận được những dữ liệu này trong bạn HttpPost phương pháp hành động, nếu bạn điền vào đó khỏi tầm nhìn của bạn .

enter image description here

+0

Điều gì sẽ xảy ra nếu mô hình của tôi chứa một số dạng xemModel làm thuộc tính? Ví dụ Người có tài sản Nghề nghiệp với các tài sản khác? – Radislav

+0

@Radislav: Đúng vậy. Kiểm tra câu trả lời cập nhật của tôi. – Shyju

+0

Exelent !!! Cảm ơn rất nhiều!!!! – Radislav

7
var myData = { 
       Parameter1: $("#someElementId").val(), 
       Parameter2: $("#anotherElementId").val(), 
       ListParameter: { /* Define IEnumerable collections as json array as well */} 
       // more params here 
      } 
$.ajax({ 
    url: 'someUrl', 
    type: 'POST', 
    dataType: "json", 
    contentType: 'application/json', 
    data: JSON.stringify(myData) 
}); 


[HttpPost] 
public JsonResult Create(CustomViewModel vm) 
{ 
    // You can access your ViewModel like a non-ajax call here. 
    var passedValue = vm.Parameter1; 
} 

Bạn cũng có thể tuần tự hóa toàn bộ biểu mẫu và chuyển nó sang phương thức hành động của bộ điều khiển. Trong bạn ajax gọi:

data: $('form').serialize() 
+0

Tuyệt vời !!! Tôi không biết rằng nó sẽ hoạt động. Cảm ơn. Tôi sẽ kiểm tra và uswer cho bạn. – Radislav

Các vấn đề liên quan