Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - Causing server-side page validation to fire on button click, using an AJAX call

On an app I'm working on, I have a requirement that, upon clicking a certain button, validation fires on some related textboxes; if they do not pass, nothing occurs, otherwise an action that is fired from an AJAX call occurs. This AJAX call returns some message about the success of the operation.

My partial view this is occurring in looks a bit like this:

<div>
  <div id='cell-phone'>
    @Model.ValidationMessageFor(x=>x.Model.CellNumber)
    @Model.TextBoxFor(x=>x.Model.CellNumber)
  </div>
  <div id='pager'>
    <!-- Ditto, only x.Model.Pager; yes, some people use pagers still. -->
  </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>

...down 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: while I am able to get the message/success values back, I also need to cause the View Model's validations to fire. I don't see how to do this using an AJAX call. My suspicion is that either A) I'm using the wrong tool for the job, or B) I'm using the right tool for one job, but I need something else. What am I missing to be able to cause validations to fire?

like image 643
Andrew Gray Avatar asked Dec 01 '25 14:12

Andrew Gray


1 Answers

When you click on 'test-pager' link, the action will be called but the validation of your form doesn't trigger because your link is not a submit. If you want to validation work you must have a submit button on the form. When the user clicks it the validation will fire. So change the test-pager to something like this:

<input type="submit" id="test-pager" class="button" />
like image 99
Bahman Avatar answered Dec 03 '25 05:12

Bahman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!