Chris Pickford
Chris Pickford

Reputation: 9001

MVC ModelState validation failing for null value

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?

Upvotes: 2

Views: 1579

Answers (1)

haim770
haim770

Reputation: 49133

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.

Upvotes: 6

Related Questions