基于2个属性的复杂远程验证

时间:2016-09-07 22:14:45

标签: c# asp.net-mvc

我正在尝试使用自定义远程验证来相互验证2个属性,但没有成功。

动作

仅编辑,无插入

属性

这两个属性都是自由文本(无下拉列表)

  • 文件夹名称
  • 文件名

验证条件

  • 即使文件夹名称存在,FileName也可以为空

  • 只有文件夹名称存在时才能填写FileName

  • 每个唯一文件夹的文件名都是唯一的

  • 当加载编辑页面时,如果已存在数据,则除非用户修改这些值,否则不应进行检查。

代码

控制器中的

1- Json功能

public JsonResult IsFileValid(string folderName, string fileName)
    {
        if (!folderName.IsNullOrEmpty() && fileName.IsNullOrEmpty())
        {
            // FileName can be empty even if Folder name is present
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        if (folderName.IsNullOrEmpty() && fileName.IsNullOrEmpty())
        {
            //FileName can be empty even if Folder name is present
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        if (folderName.IsNullOrEmpty() && !fileName.IsNullOrEmpty())
        {
            //FileName can only be filled in if Folder name is present
            return Json(false, JsonRequestBehavior.AllowGet);
        }

        var Folder =
            Uow.Folders.GetAll()
                .FirstOrDefault(x => x.Name.ToLower().Trim() == folderName.Trim().ToLower());



        if (Folder != null)
        {
            // the Folder already exists, FileName name should be unique.
            return Uow.Files.GetAll()
                .Any(
                    x =>
                        x.FolderId == Folder.Id &&
                        x.fileName.Trim().ToLower() == fileName.Trim().ToLower()) ? Json(false, JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
        }
        // Folder name is new, in this case we can add new Folder and basked name
        return Json(true, JsonRequestBehavior.AllowGet);
    }

2-创建Custome远程属性类

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // When using remote attribute, we specify the controller, action and the error message. The aim of the following is to retrieve the controller, action and error message
        //using reflection.

        // first get the controller
        Type controller =
            Assembly.GetExecutingAssembly()
                .GetTypes()
                .FirstOrDefault(
                    type =>
                        type.Name.ToLower() ==
                        string.Format("{0}Controller", this.RouteData["controller"].ToString()).ToLower());
        if (controller != null)
        {
            // Get the method in the controller with
            MethodInfo action =
                controller.GetMethods()
                    .FirstOrDefault(method => method.Name.ToLower() == this.RouteData["action"].ToString().ToLower());
            if (action != null)
            {
                // create instance of the controller
                object instance = Activator.CreateInstance(controller);

                //invoke the action method of the controller, and pass the value which is the parameter of the action
                object response = action.Invoke(instance, new object[] {value});

                // because the remote validation action returns JsonResult
                var returnType = response as JsonResult;
                if (returnType != null)
                {
                    object jsonData = returnType.Data;

                    //because the jsonDate is bool
                    if (jsonData is bool)
                    {
                        // return success or the error message
                        return (bool) jsonData ? ValidationResult.Success : new ValidationResult(this.ErrorMessage);
                    }
                }
            }
        }
        return new ValidationResult(ErrorMessage);
    }

3-我的viewModel类

 public class FileInViewModel
    {

        public string FolderName { get; set; }

        [RemoteValidation("IsFileValid","Home",ErrorMessage="Please select different file name")]
        public string FileName { get; set; }

        // .....
    }
  • 我错过了什么才能让它发挥作用?如果也可能有不同 每个错误的错误消息?
  • 如何在加载编辑页面时忽略已存在数据的验证?

1 个答案:

答案 0 :(得分:1)

请参见下面的代码:

[Remote("CheckExist", "securitylevels", AdditionalFields = "Id", ErrorMessage = "the number is Zero!")]
public int Number { get; set; }