Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi POST not to include ID field

I am still just a couple days into ASP.NET and WebAPI frameworks so I must be missing out something really simple.

I have a model that has a couple properties and ID (as a property, which has a private setter but that didn't help).

public long ID { get; private set; }

[Required(ErrorMessage = "Location coordinate X is required.")]
public double X { get; set; }

[Required(ErrorMessage = "Location coordinate Y is required.")]
public double Y { get; set; }

And then I have a controller method post:

public HttpResponseMessage Post(MyModel model)

When I start the project and go to auto-generated API documentation, I can see that samples include ID as an input field. I want API to ignore ID input field. I could just ignore it myself but I don't like such must-remember-not-to-use things in my code.

One option would be to create a separate model just for the input but it would mean I have to maintain two classes instead of one.

Is there any data annotation to ignore this property entirely?

like image 447
Pijusn Avatar asked Oct 15 '13 07:10

Pijusn


1 Answers

Try with:

[ScaffoldColumn(false)]

The ID property will no longer be seen by the html helpers. However, the model binder might still try to move a value into the ID property if it sees a matching value in the request.

So you decorate it with Exclude to avoid property to be binded:

[Exclude]
 public long ID { get; set; }

You can also , (inside your Post function) remove the property from state:

  ModelState.Remove("Id"); // Key removal

    if (ModelState.IsValid)
       {

       }
    }
like image 82
Carlos Landeras Avatar answered Oct 06 '22 21:10

Carlos Landeras