简体   繁体   English

MVC5 ViewModel验证远程

[英]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: 我在Controllers目录中有一个名为“ValidationController.cs”的控制器,该控制器包含以下内容:

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? 然而, CheckUsername方法甚至没有被击中,我做错了什么?

Thank you. 谢谢。

The property name on the model and the parameter of the CheckUsername function need to be equal. 模型上的属性名称和CheckUsername函数的参数必须相等。 I think they are not case sensitive. 我认为它们不区分大小写。 Try with: 试试:

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

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: 在您的Web配置文件中,您有:

  <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. 您需要使用提交按钮在<form>中包含以前的文本,以便能够验证用户名。 It's not automatically as Regex, Required or StringLength. 它不会自动为Regex,Required或StringLength。 I think this works that way to avoid request the server until the user is sure that's the Username he wants. 我认为这样可以避免请求服务器,直到用户确定是他想要的用户名。

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. 必须在视图中引用jquery,jquery.validate和jquery.validate.unobtrusive脚本,并且视图中用户名字段的html name属性必须与CheckUsername方法的输入匹配,因此这将起作用。

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

but this may cause model binding issues since your property is public string Username { get; set; } 但这可能会导致模型绑定问题,因为您的属性是public string Username { get; set; } public string Username { get; set; } public string Username { get; set; } , so the best practice is to keep all of them the same. public string Username { get; set; } ,所以最好的做法是,让所有的人都一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM