MVC5视图模型验证远程 [英] 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; }
}
我有一个名为ValidationController.cs的控制器目录中的控制器,该控制器包含以下内容:
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);
}
}
}
然而,它的 CheckUsername
方法甚至没有被打到,我究竟做错了什么?
However it the CheckUsername
method doesn't even get hit, what am I doing wrong?
感谢您。
推荐答案
让我们仔细检查两件事情:
Let's double check a couple of things:
您已经正确地引用在布局以下库(preferably),并按此顺序:
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>
在您的Web配置文件有:
On your web config file you have:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
在您的看法是这样的:
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username)
@Html.ValidationMessageFor(m => m.Username)
更重要的是删除验证不火,直到你点击提交的第一次。您需要包括内部的和LT的previous文本; FORM>一个提交按钮能够验证用户名。这不是自动正则表达式,必需或StringLength。我觉得这个作品的方式,以避免请求的服务器,直到用户是肯定这是他想要的用户名。
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.
这篇关于MVC5视图模型验证远程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!