开发者

ModelState.AddModelError - How can I add an error that isn't for a property?

开发者 https://www.devze.com 2023-02-28 06:44 出处:网络
I am checking my database in Create(FooViewModel fvm){...} to see if the fvm.prop1 and fvm.prop2 already exist in that combination; if so, I want to add an error to the modelstate, then return the who

I am checking my database in Create(FooViewModel fvm){...} to see if the fvm.prop1 and fvm.prop2 already exist in that combination; if so, I want to add an error to the modelstate, then return the whole view. I tried:

public ActionResult Create(FooViewModel fvm){
    if (ThatComboAlreadyExists(fvm)) {
      ModelState.AddModelError("Model", "There is already one like that");
      return View(fvm);
    }
}

...but I get no display of errors in the Html.ValidationSummary, which is where开发者_如何学JAVA I assume they would appear. I have the suspicion that "Model" is not the right key, but I haven't been able to find anything a la Google.


I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.


You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.

As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using

<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and

ModelState.AddModelError("Email", Resources.EmailInUse);


Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");


Try Using Below Answer for consistent Output Format :- new ValidationProblemDetails()

if (!ModelState.IsValid) { 
ModelState.AddModelError("ErrorKey", "ErrorValue");
return BadRequest(new ValidationProblemDetails(this.ModelState));
}

Output Format:

{
    "errors": {
        "ErrorKey": [
            "ErrorValue"
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号