我試圖在JavaScript中創建一個模型,並通過$ http.post將其發佈到ASP.NET MVC控制器方法。當檢查發佈的JSON時,我的Address
屬性被填充。但是,當ASP.NET MVC控制器被擊中時,所有對應的地址屬性都爲空。將AngularJS模型發佈到ASP.NET MVC控制器中的複雜模型
角控制器的方法:
$scope.submitForm = function(isValid) {
alert("Form is valid!");
var member = {
TempCardNumber: $scope.tcardno,
Title: $scope.title,
FirstName: $scope.firstName,
LastName: $scope.lastName,
Address: [
{
AddressLine1: $scope.address1,
AddressLine2: $scope.address2,
AddressLine3: $scope.address3,
AddressLine4: $scope.address4,
TownCity: $scope.towncity,
County: $scope.county,
PostCode: $scope.postcode,
PhoneNumber: $scope.phone
}
],
EmailAddress: $scope.email
};
$http({
method: 'POST',
url: '/Home/Index',
data: member
}).success(function (data, status, headers, config) {
});
}
發佈JSON:
{"TempCardNumber":"633341677489986320","Title":"Mr","FirstName":"test","LastName":"user","Address":[{"AddressLine1":"8 Eaton Close","AddressLine2":" Hatton","TownCity":" Derby","County":" Derbyshire","PostCode":" DE65 5ED","PhoneNumber":""}],"EmailAddress":"[email protected]"}
ASP.NET MVC控制器:
public ActionResult Index([FromBody]MemberModel model)
{
// do stuff
}
我試過字符串化-ING的JSON,傳遞在我的Angular文章中只有data: member
,並且在ASP.NET MVC方法上使用[FromBody]
,但總是,model.Address
屬性爲空。
有無論如何我可以做到這一點,而無需將每個屬性發布到我的ASP.NET MVC控制器?
編輯:新增MemberModel POCO爲清楚起見
// MemberModel class
public string Title {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public Address Address{get;set;}
public string TempCardNumber {get;set;}
public string Email {get;set;}
// Address POCO
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string AddressLine3 {get;set;}
public string AddressLine4 {get;set;}
public string TownCity {get;set;}
public string County {get;set;}
public string Postcode {get;set;}
public string PhoneNumber {get;set;}
'BindModel'應該在什麼地方...如果在您的POST事件服務器端,它應該基於輸入類型的模型進行綁定,如果沒有,則該對象無法正確轉換。殘友向我們展示您的類模型'MemberModel'? – Pogrindis
您是否需要在某處設置內容類型,以便告訴ASP.NET MVC您正在發佈JSON?嘗試爲你的'$ http'請求添加'headers:{「Content-Type」:「application/json」}'。 – Chris
MemberModel class added – Brett