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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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
    //...
    }

Method 3

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x