javascript 在 ASP.NET MVC 应用程序中使用 AngularJS 发布表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26022695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:23:24  来源:igfitidea点击:

Post an form using AngularJS in an ASP.NET MVC application

javascriptasp.net-mvcangularjsrazor

提问by Kris-I

I'd like to post the form using AngularJS. The code below work, I mean when I launch the application, the form is filled in with the values coming from the controller ok. When I type in the textbox (the one with ng-model="sometext") the content of H1 change, that's means AngularJS is present and working.

我想使用 AngularJS 发布表单。下面的代码有效,我的意思是当我启动应用程序时,表单中填充了来自控制器的值。当我在文本框(带有 ng-model="sometext" 的那个)中输入 H1 的内容时,这意味着 AngularJS 存在并且正在工作。

The problem is when I press the submit button, the form is not posted. The sendFormis called (I tested with an alert), no error in the console.

问题是当我按下提交按钮时,表单没有发布。在sendForm被称为(我与警报测试)在控制台中,没有错误。

In the console

在控制台中

XML : 
XML Parsing Error: no element found Location: moz-nullprincipal:{9bd871b4-ae27-4998-a67a-bc2674aefe60} Line Number 1, Column 1:
^
Post : is blank
Cookies : 
__RequestVerificationToken : JyEiABS8lLKnblGCkeLg_ODieIZc4ZhjHn6lEo4o9geEB9_lgEjxiYBtJ-zligkONM2sxSBgDgvpMolF3derhg6KuUXf2vKNSEVIRVtSwes1
Headers :
Cache-Control   private
Content-Length  0
Date    Wed, 24 Sep 2014 17:02:19 GMT
Server  Microsoft-IIS/8.0
X-AspNet-Version    4.0.30319
X-AspNetMvc-Version 5.2
X-Powered-By    ASP.NET
X-SourceFiles   =?UTF-8?B?RDpcVXNlcnNcQ2hyaXNcTXkgRG9jdW1lbnRzXFZpc3VhbCBTdHVkaW8gMjAxM1xQcm9qZWN0c1xQT0NBbmd1bGFySlNXaXRoTVZDXFdlYkFQSVdpdGhNVkNcUGVyc29uc1xTYXZl?=
view source
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  0
Content-Type    text/plain; charset=UTF-8
Cookie  __RequestVerificationToken=JyEiABS8lLKnblGCkeLg_ODieIZc4ZhjHn6lEo4o9geEB9_lgEjxiYBtJ-zligkONM2sxSBgDgvpMolF3derhg6KuUXf2vKNSEVIRVtSwes1
Host    localhost:51853
Referer http://localhost:51853/Persons
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
X-Requested-With    XMLHttpRequest

The class :

班上 :

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

On the layout page, is the standard page created by default. I just adjust the HTML tag :

在布局页面上,是默认创建的标准页面。我只是调整了 HTML 标签:

<html data-ng-app="myApp">

PersonsController.cs in \Controllers :

\Controllers 中的 PersonsController.cs :

public class PersonsController : Controller
{
    public ActionResult Index()
    {
        return View(new Person { FirstName = "MyFarst", LastName = "MyLast", Id = 1 });
    }

    public void Save(Person person)
    {
        Console.WriteLine(person);
    }
}

Index.cshtml in \Views\Persons :

\Views\Persons 中的 Index.cshtml :

@model MyApp.Entities.Person
<div>
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
    <h1>Hello {{ sometext }}</h1>
</div>

<div>
    <div data-ng-controller="personController">
        First Name: <input type="text" ng-model="firstName"><br>
    </div>
    <form name="mainForm" data-ng-submit="sendForm()" data-ng-controller="personController" novalidate>
        <div>@Html.AntiForgeryToken()</div>
        <div>@Html.TextBoxFor(m => m.FirstName)</div>
        <div>@Html.TextBoxFor(m => m.LastName)</div>
        <div><button type="submit" data-ng-disabled="mainForm.$invalid">Submit</button></div>
    </form>
</div>

The app.js file :

app.js 文件:

var myApp = angular.module('myApp', []);
myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";

    $scope.sendForm = function () {
        $http({
            method: 'POST',
            url: '/Persons/Save'
        }).success(function (data, status, headers, config) {

        }).error(function (data, status, headers, config) {

        });
    };
}]);

回答by Marian Ban

You are mixing mvc with angularjs it will not work. You have to do this:

您正在将 mvc 与 angularjs 混合使用,它将不起作用。你必须这样做:

<div>        
    <form name="mainForm" data-ng-submit="sendForm()" data-ng-controller="personController" novalidate>        
        <div><input ng-model="model.firstName" type="text" /></div>
        <div><input ng-model="model.lastName" type="text" /></div>
        <div><button type="submit" data-ng-disabled="mainForm.$invalid">Submit</button></div>
    </form>
</div>

javascript:

javascript:

var myApp = angular.module('myApp', []);
myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
   $scope.model= {};

   $http({method: 'GET', url: 'Persons/Get' + personIdFromQueryString}).success(function(data) {
        $scope.model = data;
   });

    $scope.sendForm = function () {
        $http({
            method: 'POST',
            url: '/Persons/Save',
            data : $scope.model
        }).success(function (data, status, headers, config) {

        }).error(function (data, status, headers, config) {

        });
    };
}]);

mvc controller:

MVC控制器:

public class PersonsController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Get(int id)
    {
       return Json(new Person { FirstName = "MyFarst", LastName = "MyLast", Id = 1 });
    }

    public void Save(Person person)
    {
        Console.WriteLine(person);
    }
}