Utilizing MVC to trigger server-side page validation upon clicking a button through an AJAX request

While developing an app, I encountered a requirement where validation needs to be triggered on specific textboxes upon clicking a button. If the validation fails, nothing happens; if it passes, an AJAX call is made that triggers a certain action. This action returns a message indicating the success of the operation.

The partial view where this functionality is implemented looks like the following:

<div>
  <div id='cell-phone'>
    @Model.ValidationMessageFor(x=>x.Model.CellNumber)
    @Model.TextBoxFor(x=>x.Model.CellNumber)
  </div>
  <div id='pager'>
    <!-- Similar structure for x.Model.Pager; some users still use pagers! -->
  </div>
  <div id='page-address'>
    <!-- ... x.Model.PageAddress ... -->
  </div>
  <div id='pager-test'>
    <a href='#' id='test-pager' class='button'>Test</a>
    <span id='test-result'></span>
  </div>
</div>

<script>
var $cellNum = $('#cell-phone input'),
    $pagerNum = $('#pager input'),
    $pageAddress = $('#page-address input'),
    $testPager = $('#pager-test'),
    $testResult = $('#test-result');

$(document).ready(function () {
  $testPager.click(function () {
    pagerTest();
  });
});

function pagerTest() {
  var args = { address: $pageAddress.val() };
  $.getJSON('@Url.Action("SendTestPage")', args, function(result) {
    $testResult.html(result.Message);
  });
}
</script>

At the server level...

public JsonResult SendTestPage(string address)
{
   // SNIP: Other unnecessary details.
   var result = new EmailSendResult
                {
                  success = SendEmailMethod(address)
                };
   result.message = result.success
                    ? "Message sent!"
                    : "Couldn't send message...";

   return result;       
}

....

public class EmailSendResult
{
  public bool success;
  public string message;
}

Question: Despite successfully retrieving message/success values, I am struggling to trigger the View Model's validations using an AJAX call. I suspect that either A) I am utilizing the wrong approach for this task, or B) I am using the correct approach for one task but missing something crucial. What do I need to do in order to trigger the validations?

Answer №1

Clicking on the 'test-pager' link will trigger the action, but your form validation won't activate because the link is not a submit button. To make the validation work, you need to have a submit button within the form. When the user clicks on it, the validation process will be initiated. Therefore, consider changing the test-pager link to something like:

<input type="submit" id="test-pager" class="button" />

Answer №2

Alternatively, you may want to consider binding the event listener for changes in the address text box and triggering the testPage function from within it.

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

Customize the date format of the Datepicker in Angular by implementing a personalized pipe

I am dealing with a datepicker that defaults to the MM/dd/yyyy format, and I need it to adjust based on the user's browser language. For example, if the browser language is English India, then the format should be set to dd/MM/yyyy as shown below. Be ...

Create bouncing objects with Three.js when clicking the mouse

Hello everyone, I recently started diving into Web Gl and I'm using Three js. One of my first projects involved creating a simple rotating cube in space. Now, I want to take it a step further and add some animation to the cube. For example, I'd ...

Can you explain the use of the 'this' keyword in map() and call() functions?

Recently, I've been revisiting my understanding of how to use call() and map() with a NodeList in JavaScript. It was quite easy to find information on how call() works, and there are plenty of examples of how it can be used with map(). However, whil ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Issue with ng-change function causing data not to load properly

I have added a data-ng-change='getSubjectsClasswise(classBean.class_id);' in the class <select> tag, but for some reason the subjects are not loading in the subject <select> tag. I have checked everything and it all seems fine, b ...

JSON data in Google Sheets

Hey there, I'm just starting out in c#. I recently managed to convert some JSON data from Google Sheets and now I'm trying to use it to create a leaderboard for my Unity game. However, I'm struggling to assign these "values" to a variable. I ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

What is the functionality of the keydown event?

Whenever the input text value is not empty, I want my .removetext div to be displayed, but it's not working correctly. When I type something after the second character, my .removetext gets hidden, but it shouldn't be hidden when the input is not ...

Using Moment JS to Retrieve Month Names from the Current Year Starting from the Current Month and Beyond

In my quest for knowledge, I desire to ascertain the name of the current month and also list out the remaining months in the current year that have yet to pass. As an illustration, if the current month is July and we are in the year 2021, the months of Aug ...

The LoginStatus redirect feature is limited to functioning solely in the Internet Explorer

I have been working with the Membership system on my project's masterpage and I am currently facing an issue with implementing a LoginStatus control that allows users to log in and log out. The login/logout link within the control seems to be working ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

Bypass JWT signature verification in Nestjs with passport-jwt

I am faced with a challenge where I need to access a user's secret stored in Redis by parsing the token body. Is there a more elegant solution available without having to write an entire new strategy from scratch? I am using nestjs for my architecture ...

Handling multiple render calls and rerenders in React function components with setTimeout (best practice for firing multiple times)

Is there a way to optimize the Notification component in my App, so that the setTimeout function is only initialized once even if multiple notifications are pushed into the state? function Notification(props) { console.log("Notification function compone ...

Adjust the div class to align with its content

I am looking to modify the code in order to copy the text of a div to its own class. Currently, the code provided copies text from all sibling div elements, but I specifically want each individual div's text to be its own class. For example, with the ...

Finding the maximum date using a subquery in LINQ

I am struggling with selecting a record that joins to another table based on status and an insert DateTime. My goal is to retrieve the record that corresponds to the AgreementStatuses with the highest Date_Created value. from c in Agreements join a i ...

The size of the array remains static

I seem to be encountering an issue with adding API response data to an array. The array's length remains at 1 and does not reflect the appended responses. After receiving a response from the Watson API, I add it to an array. Subsequently, when I call ...

Using jQuery UI to create a bouncing effect on a CSS sprite image

Want to give your social icons a bounce effect using jQuery UI Bounce? I'm following a template and some jQuery documentation, but having trouble getting it right. It seems like the sprite image for the icons might be causing the issue. Can someone h ...

Tips for ensuring that the "this" in React ES6 static method is bound to the lexical scope

Currently in React with ES6 via babel, my goal is to develop a static method that can update the state of the Component it belongs to by accepting an object as an argument. However, I'm facing an issue where "this" is not bound to the lexical scope. ...

Prioritize loading the JS function before initiating PHP validation

My current challenge involves calling a JavaScript function from PHP upon form submission. The error message I am encountering indicates that the function is not defined. This issue arises because PHP is loaded before JavaScript, resulting in the function ...

Utilizing jQuery, Ajax, and PHP to create an Interactive Cascade Selection Box

I am working on a University project where I need to create two select boxes for Manufacturer and Model. The selection made in the Manufacturer box should determine the query that will be executed to populate the Model box. However, it seems like there is ...