MVC5 ViewModel Validation Remote
Asked Answered
S

3

4

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.

Svensen answered 20/5, 2016 at 20:30 Comment(0)
E
2

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.

Extramundane answered 21/5, 2016 at 18:16 Comment(3)
Hi, okay going through it seems that I do have everything you have mentioned, however in my _Layout.cshtml file I have the following lines: @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap")Svensen
@MrDKOz You can put the links directly or use bundles like you have. Just confirm that the bundle bundles/jquery on App_Start/BundleConfig.cs is including the three you need: jquery, jquery.validate and jquery.validate.unobtrusive. If you check the source code of the page in the browser it needs to include the three scripts.Extramundane
Sorted. Thank you so much! In the end it was the bundle that was missing these references.Svensen
E
1

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
    //...
    }
Extramundane answered 20/5, 2016 at 22:9 Comment(1)
Hi Carlos, thanks for the reply! I've tried changed the parameter name (also changed in the above code) and it's still not even hitting the CheckUsername function - confirmed this by placing a breakpoint inside the function itself.Svensen
H
0

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.

Hannie answered 20/5, 2016 at 22:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.