最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Post an form using AngularJS in an ASP.NET MVC application - Stack Overflow

programmeradmin4浏览0评论

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 ing 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.

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

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 data-ng-app="myApp">

PersonsController.cs in \Controllers :

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 :

@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 :

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) {

        });
    };
}]);

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 ing 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.

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

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 data-ng-app="myApp">

PersonsController.cs in \Controllers :

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 :

@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 :

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) {

        });
    };
}]);
Share Improve this question asked Sep 24, 2014 at 17:10 TheBoubouTheBoubou 19.9k54 gold badges151 silver badges249 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

<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:

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:

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);
    }
}
发布评论

评论列表(0)

  1. 暂无评论