"The ModelState represents a collection of name and value pairs that were submitted to the server during a POST." That is the best definition I have found for the ModelState property. So I have some code using a web api that Creates a customer and Updates a customer, and my question is, since I have accessed ModelState in CreateCustomer, wont the ModelState always be not valid if I hadnt already submitted a Post request with CreateCustomer? Or is the ModelState updated with both PUT and Post requests? Because according to the definition above, the ModelState property wont be initialized until I create a customer, and in my UpdateCustomer method, I need to check if the customer object given in the parameters is the one that is valid, not any Model that was submitted to the server during a different POST request.
[HttpPost]
//If we name it PostCustomer, we dont have to put the httppost tag
public Customer CreateCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
_context.Customers.Add(customer);
_context.SaveChanges();
return customer;
}
// Put /api/customers/1
[HttpPut]
public void UpdateCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
Customer customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customerInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
customerInDb.Name = customer.Name;
customerInDb.Birthdate = customer.Birthdate;
customerInDb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
customerInDb.MembershipTypeId = customer.MembershipTypeId;
_context.SaveChanges();
}
Code is from Mosh Hamedani's ASP.Net MVC course. Link to the ModelState definition. https://exceptionnotfound.net/asp-net-mvc-demystified-modelstate/