You can use ASP.Net MVC Partial View and JQuery Ajax.
In your Controller create a method that returns a PartialView:
public PartialViewResult CheckNickname(string nickname)
{
if (Nicknames.GetNicknames().Exists(x => x == nickname))
ViewBag.StatusNickName = "Nickname existe";
else
ViewBag.StatusNickName = "Nickname não existe";
return PartialView();
}
Right click on the CheckNickname method and click on "add view". When you open the View settings window check the "Create as partial view" box.
InyourPartialViewyoucanputthevalidationmessageofthenickname,IusedaViewBagtoreturnthemessage(onlyhasthiscodebelowinthepartialview):
<h1>@Html.ViewBag.StatusNickName</h1>
NowyouneedtorenderPartialViewsomewhereinyourRegistrationView:
<divid="checkNicknameDiv">
@{
Html.RenderPartial("CheckNickname");
}
This is Ajax that will call the method that returns the partial view:
<script type="text/javascript">
function checkNickname() {
$.ajax(
{
type: 'GET',
url: '/User/CheckNickname',
data: { nickname: $('#nickname').val() },
dataType: 'html',
cache: false,
async: true,
success: function (data) {
$('#checkNicknameDiv').html(data);
}
});
}</script>
In the parameter data
of ajax put the code that will get the value of the indication field.
To trigger the checkNickname()
function, I created a timer. When you start typing in the field, the timer waits for a second without typing to trigger the function, if you continue typing before completing one second, the timer will reset and start again.
var typingTimer; //timer
var doneTypingInterval = 1000; //tempo ms, 1 segundo por exemplo
var $input = $('#nickname'); //campo de indicação
//no keyup, cria o contador e começa a contagem
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//no keydown, elimina o contador
$input.on('keydown', function (e) {
var keyCode = e.keyCode || e.which;
//se teclar tab
if (keyCode == 9) {
checkNickname();
}
else {
clearTimeout(typingTimer);
}
});
//se o tempo acabar, chama a função
function doneTyping() {
checkNickname();
}
Any questions, just talk ... hugs!