Javascript 如何将viewmodel数据从视图传递到控制器?
目前,我的视图类似于:Javascript 如何将viewmodel数据从视图传递到控制器?,javascript,c#,angularjs,asp.net-mvc,Javascript,C#,Angularjs,Asp.net Mvc,目前,我的视图类似于: @using (Html.BeginForm("CreateUser", "Home", FormMethod.Post)) {<form ng-controller="MyController"> <table cellpadding="2" cellspacing="2"> <tr> <td>@Html.LabelFor(model =>
@using (Html.BeginForm("CreateUser", "Home", FormMethod.Post))
{<form ng-controller="MyController">
<table cellpadding="2" cellspacing="2">
<tr>
<td>@Html.LabelFor(model => model.FirstName) </td>
<td>@Html.TextBoxFor(model => model.FirstName, new { ng_model = "user.firstName" }) </td>
</tr>
<tr>
<td>@Html.LabelFor(model => model.LastName) </td>
<td>@Html.TextBoxFor(model => model.LastName, new { ng_model = "user.lastName" })) </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" ng-click="addUser()" /></td>
</tr>
</table>
</form>
}
我想知道,我应该将哪些数据从视图传递到控制器?也就是说,如何将模型从视图传递到控制器?我该如何设置角度
$scope.addUser = function() {
var data = {
//user.firstname, user.lastname but how does angular know what user is?
//User is defined as the Model on the ASP.NET MVC side.
};
$http
.post('Home/Create', data)
.success(function(data, status, headers, config) {
})
.errors(function(data, status, headers, config) {
});
};
后端模型字段应与前端模型字段相同,以便映射不会产生错误。假设您已按以下所述定义了范围,然后定义用户属性,以便angular可以将其与ng模型属性绑定
function MyController($scope) {
$scope.user= {};
$scope.addUser= function() {
console.log(this.user);
......
};
}
提交上述表单时,$scope.addUser将包含表单的一个对象,然后可以在http post请求中传递该对象。e、 g:
Object {firstName: "Test First Name", lastName: "Test Last Name"}
您可以
序列化表单
并将其作为数据发送。序列化对象将是视图的模型类型。因此,它的视图模型是UsersViewModel
,然后它将被序列化为UsersViewModel
atCreateUser
如何序列化js/angular中的表单数据?var data={FirstName:'John',LastName:'Terry'}代码>我的意思是,上面我让用户输入名字和姓氏,所以我不能这样分配它。我需要将textbox参数传递给数据。我该如何序列化它?不确定是否在angular中。但通过js,您可以执行类似于var data=$(“form”).serialize()
。它是如何知道usersViewModel的?没有
function MyController($scope) {
$scope.user= {};
$scope.addUser= function() {
console.log(this.user);
......
};
}
Object {firstName: "Test First Name", lastName: "Test Last Name"}