如何在mvc 5中自定义远程验证错误消息?

时间:2015-08-15 14:19:27

标签: validation model-view-controller

[System.Web.Mvc.Remote("CheckIdCard", "Lockers", ErrorMessage = "This Id Card have been used, Locker id is {0}{1}{2}")]
[MaxLength(18)]
public string IdCard { get;set;}

如果ID卡已存在于数据库中,则客户端将显示此记录的ID。

我应该覆盖哪种方法???

public class CustomErrMsgRemoteAttribute : System.Web.Mvc.RemoteAttribute, IClientValidatable
{
    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(name);
    }
    //public override 
}

[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public JsonResult CheckIdCard(string IdCard)
    {
        bool isValidate = false;
        string val=string.empty;
        var locker = db.Lockers.Where(l => l.IdCard == IdCard).FirstOrDefault();
        if (locker==null)
        {
            isValidate = true;
        }
        else
        {
           string val=locker.Id;
        }
        // retrun this locker.id in errormessage;
        return Json(isValidate, JsonRequestBehavior.AllowGet);
    }

我不知道如何编写这些代码,谢谢。

1 个答案:

答案 0 :(得分:0)

将其放在元数据文件或模型类

[RemoteAttribute("IsRegionCodeExists", "Region",ErrorMessage="Region Code exists,  
public string RegionCode { get; set; }

现在在控制器中

 //
    // GET: /Region/
    public JsonResult IsRegionCodeExists(string RegionCode)
    {
        return IsExist(RegionCode) ? Json(true, JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
    }

    public bool IsExist(string RegionCode)
    {
        var _model = (from s in db.Regions
                      where s.RegionCode == RegionCode
                      select s.RegionCode).FirstOrDefault();


        if (string.IsNullOrEmpty(RegionCode)) return false;

        else if (_model!=null) 
             return false;
        else return true;
    }