2

If I have the following model:

public class Model
{
    public int ModelID { get; set; }
    public string Title { get; set; }
    public DateTime Created { get; set; }
}

And the following controller method:

public ActionResult Create(Model model)
{
    if (ModelState.IsValid)
    {
        model.Created = DateTime.Now;

        // Save to DB
    }
}

In the view the Created field is hidden as I want this to populate with the timestamp of when the Create controller method is called. This fails ModelState validation due to the model.Created property being null.

I don't want to make the model.Created property Nullable but I need to somehow specify that this field isn't required in the view. Can someone please advise how to accomplish this?

4
  • move model.Created = DateTime.Now; outside the if. Commented Oct 14, 2013 at 14:15
  • I tried that but ModelState.IsValid still returns false. Commented Oct 14, 2013 at 14:21
  • what error does it give for being invalid? you can use VS property inspector to find the error. Commented Oct 14, 2013 at 14:23
  • ModelState.Values[2].Errors[0].ErrorMessage = "The Created field is required." Commented Oct 14, 2013 at 14:26

1 Answer 1

6

You'll want to exclude the Created property from binding using the [Bind] attribute, as follows:

public ActionResult Create([Bind(Exclude = "Created")] Model model)
{
    ....
}

It is also recommended for security reasons, as you don't want your client to set Created value for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.