在我的控制器中,我定義了一個Customer viewmodel類,如下所示。爲什麼MVC模型綁定正確地解析複雜的對象,如果請求由POST發出,並且如果GET發出請求不解決?
有兩個屬性名字,姓氏和第三財產訂單至極是訂單的集合
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string OrderBy { get; set; }
}
public class TestController : Controller
{
public ActionResult TestCustomer1(Customer customer)
{
return Json(customer);
}
}
我通過Ajax調用提交數據到控制器時,客戶端點擊一個按鈕,調用OnCustomerClick()
function OnCustomerClick() {
var complexObject = {
FirstName: 'Saroj',
LastName: 'K',
Orders: [{ OrderId: 1, OrderBy: 'Saroj' }, { OrderId: 2, OrderBy: 'Kumar' }]
};
var obj = { customer: complexObject };
var data2send = obj;
$.ajax({
type: "POST",
url: 'TestCustomer1',
data: data2send,
success: function (arg) { //call successfull
},
error: function (xhr) {
//error occurred
}
});
};
問題是,當動作被調用類似於上面的類型時:POST請求控制器操作中的Customer參數成功填充,而當我調用由類型執行的操作:GET將參數對象實例化爲具有設置爲null的屬性。
表示序列化對象的字符串在兩種情況下都完全相同,只更改字符串傳遞給action的方式:第一種情況是body請求,第二種情況是url參數。
請求體在POST請求 顧客%5BFirstName%5D = Saroj &顧客%5BLastName%5D = K &顧客%5BOrders%5D%5B0%5D%5BOrderId%5D = 1 &顧客%5BOrders%5D% 5B0%5D%5BOrderBy%5D = Saroj &顧客%5BOrders%5D%5B1%5D%5BOrderId%5D = 2 &顧客%5BOrders%5D%5B1%5D%5BOrderBy%5D =庫馬爾
查詢在GET串請求 /TestCustomer1?customer%5BFirstName%5D = Saroj & customer%5BLastName%5D = K客戶%5BOrders%5D%5B0%5D%5BOrderId%5D = 2 &客戶% %5Brders%5D%5B1%5D%5BOrderBy%5D = Kumar
任何人都可以啓發我這一點,爲什麼模型綁定的行爲在兩種情況下發生變化?
對於GET,它需要'變種complexObject = {姓:「Saroj」,名字:「K」,訂單[0]。 OrderId:1,Orders [0] .OrderBy:'Saroj',Orders [1] .OrderId:2,Orders [1] .OrderBy:'Kumar'}' –