如何将 javascript 对象映射到 mvc 模型?
How to map javascript object to mvc model?
我有一个如下所示的 js 对象:
$scope.docPropIdentityModel = {
Owner: {OwnerID:"", OwnerName: ""},
};
我想通过 ajax 调用将此对象发送到我的 mvc 控制器。假设控制器是这样的:
controller(test_class model)
{
}
模型如下:
test_class
{
public string Owner{get;set;};
}
我的控制器中出现空值。如何将 js 对象值映射到我的模型?
如果您使用 AngularJS,请使用 $http.get or $http.post。
控制器:
[HttpPost]
public ReturnType Foo(YourModelClass modelClass)
{
}
JavaScript:
$http({
url: url,
method: 'POST',
data: $scope.docPropIdentityModel
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
您的 json 对象包含两个不同的 class。
顶层 class 包含第二个对象(所有者)。
你应该有两个 classes:
public class TestClass {
public Owner owner;
}
public class Owner {
public String ownerId;
public String ownerName;
}
您的 JSON 具有正确命名约定的对象:
{
"owner":{"ownerId":"yourID", "ownerName":"yourOwnerName"}
}
我有一个如下所示的 js 对象:
$scope.docPropIdentityModel = {
Owner: {OwnerID:"", OwnerName: ""},
};
我想通过 ajax 调用将此对象发送到我的 mvc 控制器。假设控制器是这样的:
controller(test_class model)
{
}
模型如下:
test_class
{
public string Owner{get;set;};
}
我的控制器中出现空值。如何将 js 对象值映射到我的模型?
如果您使用 AngularJS,请使用 $http.get or $http.post。
控制器:
[HttpPost]
public ReturnType Foo(YourModelClass modelClass)
{
}
JavaScript:
$http({
url: url,
method: 'POST',
data: $scope.docPropIdentityModel
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
您的 json 对象包含两个不同的 class。 顶层 class 包含第二个对象(所有者)。 你应该有两个 classes:
public class TestClass {
public Owner owner;
}
public class Owner {
public String ownerId;
public String ownerName;
}
您的 JSON 具有正确命名约定的对象:
{
"owner":{"ownerId":"yourID", "ownerName":"yourOwnerName"}
}