1

I've got a Web API controller in .NET Core. I'm posting data to save a new comment model, and I have the AuthorID property that has a [Required] data annotation on the model.

I'm setting the AuthorID in the controller before saving. However, ModelState is always coming back stating that AuthorID field is required.

How do I keep my validations on the model in place and validate correctly in this scenario?

public async Task<IActionResult> PostComment([FromBody] Comment comment)
{
    comment.AuthorID = Utilities.GetUserId(this.User);
    comment.CreatedAt = DateTime.Now;

    if (!ModelState.IsValid) {
        ....
Ryan
  • 17,511
  • 23
  • 63
  • 88
  • Create a separate type for the incoming data that doesn't include the id https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5 – peco Jan 15 '18 at 07:17

3 Answers3

1

-You can use TryValidateModel() but first you need to clear the model state and then revalidate the model again ASP.NET MVC TryValidateModel() Issues when Model is Modified

 public async Task<IActionResult> PostComment([FromBody] Comment comment)
    {

        comment.AuthorID = Utilities.GetUserId(this.User);
        comment.CreatedAt = DateTime.Now;

        ModelState.Clear();

        if (!TryValidateModel(comment)) // the same as !ModelState.IsValid
        {
            //Failure 
        }
        //Success 
    }
Ahmed Al Jabry
  • 1,367
  • 13
  • 9
0

You can remove ModelState validation using

ModelState.Remove("AuthorID")
Riyaz K
  • 11
  • 2
  • Is there a way to do it and keep the validation? In this example AuthorID could be null, in which case I would like validation to fail. I could always write this separately, but ideally I'd like ModelState to validate with AuthorID, just after I've set it. – Ryan Jan 15 '18 at 06:51
  • Is your AuthorID Nullable in Model? – Riyaz K Jan 15 '18 at 07:03
0

Create a ViewModel and pass it to your Controller Post

public async Task<IActionResult> PostComment([FromBody] CommentModel comment) 
{}

And about other logic that you need AuthorID, Create another ViewModel for that, Why you decide to depend only on one model for everything !!.

Ahmed
  • 1,542
  • 2
  • 13
  • 21