0
votes

I have the following [post]create method on my controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="Username","Name")] Admin admin)
    {
        // I assign the current date as the value to the HireDate property
        admin.HireDate = DateTime.Today;

        if (ModelState.IsValid)
        {
            // I do the insert
        }

        return View(admin);
    }

ModelState.IsValid returns as false. I looked at the ModelState object and found that the error IS in the HireDate property, because it's a non null field and the value is still null in the ModelState object.

I don't know much about ModelState but I'm assuming it's only validating the model built with the POST call.

Is there a way to "update" the ModelState object with the new data that I assigned on the controller (admin.HireDate = DateTime.Today)?

1
I would just set the value in your Create GET method, when you send the model to the view. Or if you're going to hardcode it, just hardcode it in the insert statement and don't worry bout it in your model - Jonesopolis

1 Answers

1
votes

A more appropriate approach would be to assign the property before the Page even renders. So on your Create method that returns the original view you can do this.

  public ActionResult Create()
  {
       Admin admin = new Admin();
       admin.HireDate = DateTime.Today;

       return View(admin);

  }

You will then have to use @Html.HiddenFor(x => x.HireDate) in order for the View to be able to send it back to the Controller.