MVC. Call server side validation to trigger on button click using AJAX call.

In an application I am working on, I have a requirement that when a specific button is clicked, validation is done with some associated text fields; if they fail, nothing happens, otherwise an action happens that is triggered from the AJAX call. This AJAX call returns some message about the success of the operation.

My partial view of this goes in appearance something 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 can return post / success values, I also need to invoke the View Model checks. I can't see how to do this using an AJAX call. My suspicion is that either A) I am using the wrong tool for the job, or B) I am using the right tool for one job, but I need something else. What am I missing to be able to trigger checks?

+3


source to share


2 answers


When you click on the "test-pager" link, the action will be called, but your form validation will not be called because your link is not a submission. If you want to perform validation, you must have a submit button on the form. When the user clicks on it, the check lights up. So change your test pager to something like this:



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

      

+2


source


Or (if I understand the question correctly), you can bind the textbox change event and call the testPage function inside it.



-1


source







All Articles