Validating C # MVC using data annotations (database first)

So, I have an API that has an action with a controller post:

public HttpResponseMessage Post(Model m){
  if(!ModelState.IsValid){
    return ApiRequest.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  }
}

And here is my model:

[MetadataType(typeof(Metadata))]
public partial class MyModel {

  private sealed class Metadata {

    [Required(ErrorMessage="Sample error msg.")]
    public string Field1 {get; set;}
    // ...other fields and foreign key fields here
  }

}

As I stated in my title, I use the database first, so I created a class partialsince my models are automatically generated.

The problem is that when a validation error occurs, the result of the JSON error messages is as follows:

{
  e.Field1: "Error msg here...",
  e.Field2: "Error msg here...",
  e.DateField: "An error occurred" //This happens for any date type field even though i've specified an error message
  e: ["An error occurred", "An error occurred"] //This happens for the foreign key fields i.e. AnotherModelID, I got 2 which is why I think it has two error messages also
}

First I want to remove the prefix eon keysthe JSON result here . Then why does the error return An error occurred, although I explicitly indicated the error message? And also why the foreign key fields do not display only the prefix e?

thank

UPDATE

, , , key e e.FieldName, , , , int. int int, "e only".

+4

Source: https://habr.com/ru/post/1696049/


All Articles