受影响的mvc编辑中的远程验证

时间:2015-01-29 15:27:31

标签: asp.net-mvc asp.net-mvc-4 validation

我试图通过客户端的远程验证验证用户名,并且在创建模块中添加重复字段时工作正常,但现在它不允许我使用相同的名称编辑记录&# 39; s向我展示了我为创建定义的相同错误。我尝试了所有可能的方法但没有成功请帮助我。我已经按照这些链接但它无论如何都没有工作。

http://stackoverflow.com/questions/4778151/asp-net-mvc-3-remote-validation-to-allow-original-value    http://stackoverflow.com/questions/6407096/asp-net-mvc-3-remote-attribute-passing-3-fields

这是我迄今为止尝试过的代码。请帮助专家。

[Required]
        [Remote("IsUserAvailable", "User", HttpMethod = "Post", ErrorMessage = "User already exist.", AdditionalFields = "InitialUserName")]
        [RegularExpression(@"^(?![\W_]+$)(?!\d+$)[a-zA-Z0-9 ]+$", ErrorMessage = "Invalid UserName ")]
 public string UserName { get; set; }


[HttpPost]
    public JsonResult IsUserAvailable([Bind(Prefix = "User.UserName")]string UserName, string initialUserName)
    {

        var result = uDbContext.Users.FirstOrDefault(a => a.UserName == UserName);
        if (result == null)
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        return Json(JsonRequestBehavior.AllowGet);
    }


@model User.ViewModel.ViewModelUser
@using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        @Html.HiddenFor(m => m.User.UserId)



                @Html.LabelFor(m.User.UserName)


               @Html.TextBoxFor(m => m.User.UserName)
                @Html.ValidationMessageFor(m.User.UserName)
                @Html.Hidden("initialUserName", Model.User)
            </div>
        </div>
}

请帮助专家完成我的任务。

3 个答案:

答案 0 :(得分:5)

User似乎是一个复杂的对象,所以

@Html.Hidden("initialUserName", Model.User)

可能会产生类似

的内容
<input type="hidden" name="initialUserName" value="YourAssemly.User" ... />

这对验证没有帮助。

您可以使用

发回原始名称来忽略验证
@Html.Hidden("InitialUserName", Model.User.UserName)
@Html.Hidden("User.InitialUserName", Model.User.UserName)

然后使用

比较控制器中的值
public JsonResult IsUserAvailable([Bind(Prefix = "User.UserName")]string UserName, string initialUserName)
public JsonResult IsUserAvailable([Bind(Prefix = "User.UserName")]string UserName, [Bind(Prefix = "User.InitialUserName")]string initialUserName)
{
  if (UserName == initialUserName)
  {
    // Nothing has changed so signal its valid
    return Json(true, JsonRequestBehavior.AllowGet);
  }
  // Check if the user name already exists
  var result = uDbContext.Users.FirstOrDefault(a => a.UserName == UserName);
  return Json(result == null, JsonRequestBehavior.AllowGet);
}

附注:jquery远程验证是GET调用,因此不需要[HttpPost]属性

修改

调试jquery-validate.jsjquery-validate-unobtrusive.js文件后,发现任何AdditionalFields的name属性必须包含与要验证的属性相同的前缀,并且[Bind(Prefix="..")]然后,方法中的那些参数也需要1}}属性(参见上面的修正)

另一种方法是创建一个简单的类来回发,例如

public class ValidateUserNameVM
{
  public string UserName { get; set; }
  public string InitialUserName { get; set; }
}

public JsonResult IsUserAvailable([Bind(Prefix = "User")]ValidateUserNameVM model)
{
  if (model.UserName == model.InitialUserName)
  ....

答案 1 :(得分:0)

您的验证功能不完整。在模型的[Required]属性上添加UserName属性,然后尝试:

public JsonResult IsUserAvailable(string userName, string initialUserName)
{
   if (userName.Trim().ToLower() != (initialUserName ?? "").Trim().ToLower())
   {
       var result = YourMethodToCheckTheDatabaseForUsernameIsAvailable(userName);
       return Json(result, JsonRequestBehavior.AllowGet);
   }
   return Json(true, JsonRequestBehavior.AllowGet);
}

答案 2 :(得分:0)

对于谁在第二个参数中获得空值,这个简单的想法可能会有所帮助

public JsonResult IsUserNameAvailable(string Name, string EditNameIssue)
        {//it will return true if match found elese it will return false. so i add !
            if (Name == EditNameIssue)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(!db.Employees.Any(e => e.Name == Name), JsonRequestBehavior.AllowGet);
            }
        }

转到“班级”并将string EditNameIssue添加到班级,以便可以将其发送到控制器

[MetadataType(typeof(EmployeeMetaData))]
    public partial class Employee
    {

        public string EditNameIssue { get; set; }
    }

然后编辑“远程”属性以发送此附加属性

[Remote("IsUserNameAvailable","Employees",ErrorMessage ="User Name Already Taken",AdditionalFields = "EditNameIssue")]
        public string Name { get; set; }

如果您添加一个名称来编辑已使用的文本框,则此逻辑可能会有所帮助

public JsonResult IsUserNameAvailable(string Name, string EditNameIssue)
    {//it will return true if match found elese it will return false. so i add !
        //Edit Request  
        if (Name == EditNameIssue)
        {
            //this mean he didn't change the name
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        else if (Name != EditNameIssue)
        {
            //if he change the name in the edit go and check if the new name exist 
            //note if he modify and reenter it origin name it will be also erro he has to reload
            return Json(!db.Employees.Any(e => e.Name == Name), JsonRequestBehavior.AllowGet);
        }
        else if (string.IsNullOrEmpty(EditNameIssue))
        {//this mean you came from create request as there is no EditNameIssue in this view

            return Json(!db.Employees.Any(e => e.Name == Name), JsonRequestBehavior.AllowGet);

        }
        else
        {//just for the completeness
            return Json(false, JsonRequestBehavior.AllowGet);
        }


    }