繁体   English   中英

如何将视图模型数据从视图传递到控制器?

[英]How can I pass my viewmodel data from my view to my controller?

目前,我的观点类似于:

@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>&nbsp;</td>
                <td><input type="submit" value="Save" ng-click="addUser()" /></td>
            </tr>
        </table>
    </form>
    }

我的控制器(在ASP.NET MVC方面):

[HttpPost]
public ActionResult Create(UsersViM usersVM)
{
  //Sets the model equal to viewmodel 
  //Saves the name in session and redirects to previous view with new list of names. 
}

我想知道,应该从视图向控制器传递哪些数据? 也就是说,如何将模型从视图传递到控制器? 如何设置角度?

$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) {
        });
};
$scope.addUser = function () {
                $http
                    .post('Home/CreateUser', usersViewModel)
                    .success(function (data, status, headers, config) {
                        successFn();
                    })
                    .errors(function (data, status, headers, config) {
                        errorFn();
                    });
            };

您的后端模型字段应与前端模型字段相同,以便映射不会产生错误。

假设如果您按如下所述定义了范围,则定义用户属性,以便angular可以将其与ng-model属性绑定。

function MyController($scope) {
    $scope.user= {};

    $scope.addUser= function() {   
        console.log(this.user);
        ......
    };
}

提交上述表单后,$ scope.addUser将包含您表单的对象,然后可以在您的http发布请求中传递该对象。 例如:

Object {firstName: "Test First Name", lastName: "Test Last Name"} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM