2012-05-29 19 views

回答

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

}); 

您的視圖模型屬性名稱和參數我們傳遞應該是相同的。即:您的視圖模型應該有2個屬性稱爲FirstNameLastName像他

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

} 

和信件的操作方法應該接受類型的參數PersonViewModel

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

另外,如果你的看法是強類型來在PersonViewModel,你可以序列化形式簡單地發送到操作方法使用jQuery serialize方法

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

}); 

編輯:按照註釋

Serialize會照顧孩子財產的爲好。假設你有一個名爲職業這樣

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

類和你PersonViewModel有一個類型的屬性Profession

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

你會得到這些數據的HttpPost操作方法,如果您填寫的是從您的視圖。

enter image description here

+0

如果我的模型包含一些viewModel作爲屬性會怎麼樣?例如人有財產職業與其他財產? – Radislav

+0

@Radislav:是的,它會。檢查我更新的答案。 – Shyju

+0

Exelent !!!非常感謝!!!! – 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; 
} 

您也可以序列化整個表單並將其傳遞給控制器​​的操作方法。在你的Ajax調用:

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

太棒了!!!我不知道它會起作用。謝謝。我會檢查並向你求助。 – Radislav

相關問題