开发者

Model.IsValid is always false when I insert a datetime

开发者 https://www.devze.com 2023-02-16 23:47 出处:网络
I have the following class: public class Post { [DataType(DataType.Date, ErrorMessage=\"Please fill in a valid date.\")]

I have the following class:

public class Post
{
    [DataType(DataType.Date, ErrorMessage="Please fill in a valid date.")]
    [RegularExpression(@"^\d{1,2}\/\d{1,2}\/\d{4}$", ErrorMessage="Fill in a valid date.")]
    public DateTime? PublishDate { get; set; }
}

and in my Edit action I have it like this

[HttpPost]
public ActionResult Edit(Post post)
{
    if (ModelState.IsValid)
    {
        return RedirectToAction("Index");
    }
    else
    {
        return View(post);
    }
}

But my ModelState is always invalid. How come? How can I solve this?

I also posted here: http://forums.asp.net/t/1663783.aspx/1?MVC3+how+to+check+datetime+on+model+with+unobtrusive+javascript+.

Update: I found that there is indeed an error via:

ModelState.Values.Select(x => x.Errors);

But how can I find out how it gets there? And more important, how 开发者_如何学Gocan I solve it?


Your regular expression does not work with the date that you enter. I would simply remove it since the DateTime struct will not be assigned if the date can't be parsed by the model binder.

0

精彩评论

暂无评论...
验证码 换一张
取 消