如何在mvc中提交带角度的表格?

时间:2015-06-30 10:57:25

标签: angularjs asp.net-mvc

我有表格:

 <form ng-controller="accountContentController" name="editUserForm" action="PersonalInformation" method="post">
    @Html.TextBoxFor(m => m.ZipCode, new { id = "zipCode", name = "zipCode", @class = "form-control", @maxlength = "5", @required = "required", ng_model = "zipCode", ng_pattern = @"/[0-9]{5}$/" })
    @Html.PasswordFor(m => m.Password, new { id = "password", name = "password", ng_model = "password", @class = "form-control", @required = "required"})
    <input id="submit" type="submit" class="btn-block secondary-button save-changes" value="@Translator.Translate("SAVE_CHANGES")">
</form>

我有控制器在mvc:

  [HttpPost]
  public ActionResult PersonalInformation(PersonalInformationModel model)
   {
       return View(model);
   }

如何提交表单以便从视图向控制器发送数据?

1 个答案:

答案 0 :(得分:1)

首先,您需要在提交按钮中使用自定义ajax提交功能。

<button type="button" ng-click="submit(editUserForm)">@Translator.Translate("SAVE_CHANGES")</button>

然后在您的控制器中处理提交

$scope.submit = function(form) {
    // client side error checking
    if (form.$invalid) {
        // do something and return
    }

    // pack all parameter to match with keys in your model
    var model = {
        ZipCode: $scope.zipcode,
        Password: $scope.password
    }

    // send to your controller
    $http.post('/className/PersonalInformation', {model: model})
        .success(function(data, status, headers, config){
            // handle success here
        })
        .error(function(data, status, headers, config){
            // handle error here
        });
}

然后在你的控制器中将ActionResult更改为JsonResult

public JsonResult PersonalInformation(PersonalInformationModel model)
{
    // do something with model
    var result = doSomething(model);

    return Json(result, JsonRequestBehavior.AllowGet);
}