user863551
user863551

Reputation:

MVC5 ViewModel Validation Remote

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.

Upvotes: 4

Views: 1286

Answers (3)

Carlos Toledo
Carlos Toledo

Reputation: 2684

Let's double check a couple of things:

You have correctly referenced the following libraries in the layout (preferably) and in this order:

    <script src="~/Scripts/jquery-2.2.3.min.js"></script>    
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

On your web config file you have:

  <appSettings>    
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

On your view something like:

  @Html.LabelFor(m => m.Username)
  @Html.TextBoxFor(m => m.Username)
  @Html.ValidationMessageFor(m => m.Username)

More important the Remove validation doesn't fire until you click submit the first time. You need to include the previous text inside a < form> with a submit button to be able to validate the Username. It's not automatically as Regex, Required or StringLength. I think this works that way to avoid request the server until the user is sure that's the Username he wants.

Upvotes: 2

Amin K
Amin K

Reputation: 106

jquery, jquery.validate and jquery.validate.unobtrusive scripts must be referenced in your view, and also the html name attribute of the username field in your view must match the input of the CheckUsername method, so this will work.

<input type="text" name="p_sUsername" />

but this may cause model binding issues since your property is public string Username { get; set; }, so the best practice is to keep all of them the same.

Upvotes: 0

Carlos Toledo
Carlos Toledo

Reputation: 2684

The property name on the model and the parameter of the CheckUsername function need to be equal. I think they are not case sensitive. Try with:

    public JsonResult CheckUsername(string Username)
    {
    //change p_sUsername for Username
    //...
    }

Upvotes: 1

Related Questions