I'm trying to validate a username during the same stage as validating the view model, the rest of the validation works fine however I'm trying to use the following snippet to check if a username is already in use or not:
// Cut down code to keep it simple.
public class UserAccountRegistration
{
[Remote("CheckUsername", "Validation", ErrorMessage = "Username already exists.")]
public string Username { get; set; }
}
I have a controller named "ValidationController.cs" within the Controllers directory, that controller contains the following:
using System;
using System.Web.Mvc;
using Test.Helpers;
using System.Data.SqlClient;
using System.Data;
namespace Test.Controllers
{
public class ValidationController : Controller
{
// GET: Validation
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult CheckUsername(string Username)
{
Encryption hlpEncryption = new Encryption();
DataConnections hlpDBConn = new DataConnections();
bool bUsernameAlreadyExists = false;
string sEncUsername = hlpEncryption.Encrypt(p_sUsername);
SqlConnection conn = hlpDBConn.DBConnection();
using (SqlCommand cmd = new SqlCommand("CheckIfUsernameExists", conn) { CommandType = CommandType.StoredProcedure })
{
cmd.Parameters.AddWithValue("@Username", sEncUsername);
conn.Open();
bUsernameAlreadyExists = (Convert.ToInt16(cmd.ExecuteScalar()) > 0);
conn.Close();
}
return Json(bUsernameAlreadyExists, JsonRequestBehavior.AllowGet);
}
}
}
However it the CheckUsername
method doesn't even get hit, what am I doing wrong?
Thank you.