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?