Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为模型属性添加自定义错误消息_C#_Asp.net Mvc_Forms_Validation - Fatal编程技术网

C# 为模型属性添加自定义错误消息

C# 为模型属性添加自定义错误消息,c#,asp.net-mvc,forms,validation,C#,Asp.net Mvc,Forms,Validation,是否有方法可以覆盖从控制器为模型属性引发的默认验证错误?例如,car.make不能为null,但如果此人拼写汽车名称make错误,我想抛出一个特定错误: 模型 看法 @EditorFor(model=>model.Make,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Make,“,new{@class=“text danger”}) 控制器 public Acti

是否有方法可以覆盖从控制器为模型属性引发的默认验证错误?例如,car.make不能为null,但如果此人拼写汽车名称make错误,我想抛出一个特定错误:

模型

看法


@EditorFor(model=>model.Make,new{htmlAttributes=new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Make,“,new{@class=“text danger”})
控制器

public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
    ModelState.AddModelError("Car.Make", "Check your spelling");
    return View(car);
}

控制器中的创建方法应如下所示:

public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
    if(!checkSpelling(car.Make)) {
        ModelState.AddModelError("Make", "Check your spelling");
    }
    if (ModelState.IsValid) {
        //Save changes
    }
    return View(car);
}
您会注意到,方法
ModelState.AddModelError(string key,string errorMessage)
的第一个参数
key
在您的例子中应该是
“Make”
。参考:


无论如何,我建议实现一个类似于的自定义
ValidationAttribute

只需修改
ModelState.AddModelError(“Car.Make”,“检查拼写”)类方法

public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
     if(//Your Condition upon which you want to model validation throw error) {
        ModelState.AddModelError("Make", "Check your spelling");
      }
     if (ModelState.IsValid) {
       //Rest of your logic 
     }
   return View(car);
 }
更好的方法是将验证逻辑排除在控制器之外。如果要这样做,需要根据验证逻辑创建自定义注释。要创建自定义注释,需要创建新类并在类中实现
ValidationAttribute

 public class SpellingAttributes: ValidationAttribute  
 {
 } 
下一步,您需要覆盖
IsValid()
,并在其中编写验证逻辑

protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
{  
    //validation logic 

   //If validation got success return ValidationResult.Success;
    return ValidationResult.Success;  
} 
在模型类中,可以直接使用如下注释

public class Car
{
     public int ID { get; set; }
     [Required]
     [Spelling(ErrorMessage ="Invalid Spelling")
     public string Make { get; set; }
}

有关如何在MVC中创建自定义批注的更多详细信息,请参阅我的“希望它能帮助您”。

我将实现自定义
DataAnnotation
属性,并将其用于
汽车。进行属性验证

下面是它的实现框架:

public class CheckSpellingAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        string stringValue = value as string;
        if (string.IsNullOrEmpty(stringValue) != false)
        {
            //your spelling validation logic here
            return isSpellingCorrect(stringValue );
        }
        return true;
   }
}
稍后,您可以在模型上使用它,如下所示:

public class Car
{
     public int ID { get; set; }

     [Required]
     [CheckSpelling(ErrorMessage = "Check your spelling")]
     public string Make { get; set; }
}
你的观点不会改变,行动会简单得多

public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
    return View(car);
}
public ActionResult创建([Bind(Include=“Make,Model”)]Car)
{
if(ModelState[“Make”]==null)
{
var innerModelState=new ModelState();
innerModelState.Errors.Add(“检查拼写”);
添加(新的KeyValuePair(“Make”,innerModelState));
}
返回视图(car);
}

它不是
.AddModelError(“Car.Make”,…)
它的
.AddModelError(“Make”,…)
-您的模型不包含名为
Car
的属性。但是,如果您只想从有效值中选择,请考虑使用<代码> <代码>元素(或jQuery AutoRebug)。我的表单使用Ajax来检查用户提交给CAR.SUP的结果是否在提交表单之前有效。为了验证用户提交的内容,我需要将表单值作为变量传递给DataAnnotation。然而,我认为这是不可能的。看完这篇文章。是这样吗?
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
    return View(car);
}
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
    if (ModelState["Make"] == null)
    {
        var innerModelState = new ModelState();
        innerModelState.Errors.Add("Check your spelling");
        ModelState.Add(new KeyValuePair<string, System.Web.Mvc.ModelState>("Make", innerModelState));
    }

    return View(car);
}