Leverage the power of Angular to submit a form to the ASP.NET MVC ActionMethod

I am exploring how to make an ASP.NET MVC form automatically post back to the server using angularjs. The idea is that when a field reaches a certain number of characters and passes validation, the form will automatically submit the ActionResult method that I have set up.

Question: Can I utilize angular to send a form post to the receiving method and automatically submit the form after validation? Is it possible to incorporate MVC helpers for validation?

@model model.example

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal" ng-app="receiveApp" data-ng-submit="sendForm()" , data-ng-controller="breakDownController">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.Id, new { @class = "control-label col-xs-12 col-sm-2" })
            <div class="col-sm-10">
                @Html.EditorFor(model => model.PId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Uid, new { @class = "control-label col-xs-12 col-sm-2" })
            <div class="col-sm-10">
                @Html.EditorFor(model => model.Uid, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Uid, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LId, new { @class = "control-label col-xs-12 col-sm-2" })
            <div class="col-sm-10">
                @Html.EditorFor(model => model.LId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d3c4c9d0c098e5f7c0d6cad0d7c6c0d68bf7c0c6c0ccd3c0">[email protected]</a> class="btn btn-default" />
                @Html.ActionLink(Resources.ClearButton, "Receive", null, new { @class = "btn btn-default" })
            </div>
        </div>
    </div>
}

Javascript

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



        $scope.sendForm = function () {
            $http({
                method: 'POST',
                url: '@Url.Action("Receive")',
                data: $scope.model
            }).success(function(data,status,headers,config){

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

Answer №1

Here is a code snippet that I believe can be helpful:

angular.module('formExample', [])
  .controller('FormController', ['$scope',
    function($scope) {
      $scope.userType = 'samo';
      $scope.email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8efdefe3e1cee9e3efe7e2a0ede1e3">[email protected]</a>"
      $scope.$watch(function() {
        if ($scope.myForm.$valid) {
          submitted()
        }


      });

      function submitted() {
        console.log("Form submited");
      }
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>
</head>

<body ng-app="formExample">
  <form name="myForm" ng-controller="FormController" class="my-form">
    userType:
    <input name="input" ng-model="userType" required>
    <input type="email" ng-model="email" required>
    <span class="error" ng-show="myForm.input.$error.required">Required!</span>
    <br>
  </form>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Ionic v1 modal is being destroyed prematurely, interrupting the leave animation before it

While using the default slide-in-up animation for an Ionic (v1) modal, the leave animation works flawlessly. However, when I switch to a different animation (specifically, slide-in-right), the modal is being destroyed (i.e., removed from the DOM) before th ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

Accessing the camera or photo library in React Native does not require any permissions

In my current project, I am developing an app that requires users to upload images from their photo library or camera. To access the camera functionality, I am utilizing the react-native-image-picker library without integrating react-native-permissions. ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Unable to capture Angular 401 error

My attempts to capture 401 responses from an API have been unsuccessful and quite frustrating. Every time I click on a specific link, the browser console displays a 401 response. My goal is to automatically redirect it to the login page whenever this happ ...

Advantages of using JsonResult instead of ActionResult

I've been searching high and low for a clear answer to this question. I've scoured various forums and discussions like the one found at this link, but all I've gathered is that JsonResult has a fixed content type and no noticeable performanc ...

What is the best way to send data back to a separate JavaScript file in ExtJS when working with records in a

I'm currently working on implementing a pop-up editing feature on a grid in extjs4. Progress so far includes successfully transferring the grid record to a popup panel located in a separate JavaScript file using the following code: handler: function( ...

What is the best way to apply a filter to an angular directive for filtering data in an ng-repeat loop?

Having some trouble setting up a directive where I can pass both the data and a specific filter to be used in the ng-repeat. My current approach doesn't seem to be working, so I might need to rethink my strategy. Any suggestions on how I can pass in ...

Issue: ENOENT - The specified file or directory cannot be found while scanning in a discord bot

Recently, I decided to try my hand at creating discord bots even though I am new to it. After watching a tutorial and copying the code, I encountered an error that has me stumped: node:internal/fs/utils:347 throw err; ^ Error: ENOENT: no such ...

What method does Node.js use to determine if the initial parameter in a callback function is designated as an error handler?

Recently, I've been delving into the world of Node.js and trying to grasp its error-first callback style. I'm intrigued by how a function discerns whether the first parameter is meant for handling errors or for other purposes, especially conside ...

What is the reason behind Typescript's `for...of` creating a copy of the iterable object before iterating through it

For instance: let myList = []; for (let item of myList) { ... } After being transpiled: var myList = []; for (var _i = 0, myList_1 = myList; _i < myList_1.length; _i++) { var item = myList_1[_i]; } Why is myList_1 necessary in this case? You ca ...

Utilize React's debounce feature in conjunction with updating state using

Introduction Let's discuss the popular debounce function provided by lodash. Imagine a scenario where a user rapidly enters values like 1, 12, 123, 1234. The debounce function ensures that only one alert, with the final value 1234, is triggered afte ...

How can I retrieve an Angular application's $templateCache from the global scope?

Looking for a way to efficiently share cached template strings across different JavaScript libraries? I need to utilize $templateCache.get("TEMPLATE.HTML") within an Angular app that is accessible in the public JavaScript scope. If anyone has any suggesti ...

What is the process for transforming the result of a .aspx file into a JSON format?

I am trying to convert the output of an .aspx page into a JSON object in order to accommodate a JSONP Ajax request. Here is what's happening on the page: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="mypage.aspx.cs" Inherits="folder_myp ...

What steps do I need to take in order to make the navbar-collapse function properly with an animated

After successfully implementing a collapsible navbar with a hamburger icon for mobile view, I decided to add some extra styling and animation to the hamburger button. However, now the hamburger button remains visible even in desktop view, which is not what ...

Preventing the closure of a Nativescript Angular modal when tapping on the background

I'm relatively new to NativeScript and I'm trying to figure out how to prevent my custom modal from closing when the user taps on the background, specifically for Android devices. It's easy to achieve this with the dialogs provided by Nativ ...

What is the best way to prevent duplicating a function inside a loop that retrieves a participant with a specific name matching the current looped item?

My question couldn't fit in the title, so here it is. Currently, I have a loop that generates a div element for each match, and within that div, I want to display the information of ONE of the 10 match participants. To achieve this, I am using a func ...

Can I integrate a personalized script into the ScriptManager?

One feature I really like about ASP.NET is the ScriptManager's ability to have a composite section where you can specify multiple javascript files and it will automatically merge them into one file at runtime. For example: //input scriptB.js, script ...

Exploring Next.js Font Styling and Utilizing CSS Variables

I'm attempting to implement the "next" method for adding fonts, but I find the process described quite complex just to preload a font. I experimented with exporting a function to create the font and then using a variable tag to generate a CSS variabl ...

Verify whether an image is present without actually displaying it

I am currently integrating a script for hover-functionality: function VerifyImage(url) { var httpRequest = new XMLHttpRequest(); httpRequest.open('HEAD', url, false); httpRequest.send(); return httpRequest.status != 404; } The c ...