ASP. NET MVC3 Modelstate.isvalid to False

Source: Internet
Author: User

model validation is usually validated before the action is invoked after the submit , eg:

public class Zhengxing
{
[Key]
public int Zhengxingid {get; set;} Use the key keyword to refer to System.ComponentModel.DataAnnotations


[DisplayName ("title")]
[Required (errormessage = "Please enter title")]
[MaxLength (errormessage = "title length cannot be greater than 60 characters.")]
public string Title {get; set;}


[DisplayName ("content")]
[Required (errormessage = "Please enter content")]
[MaxLength (8000, errormessage = "The content length cannot be greater than 8,000 characters.")]
public string Content {get; set;}


[DisplayName ("author")]
[Required (errormessage = "Author cannot be empty")]
public string Author {get; set;}


[DisplayName ("Creation Time")]
Public DateTime createdate {get; set;}


[DisplayName ("reading Times")]
public int Clickcount {get; set;}
}
}

Public ActionResult Create ([Bind (exclude= "Zhengxingid")]zhengxing zhengxing)
{
Zhengxing. Author = session["UserName"]. ToString ();
Zhengxing. CreateDate = DateTime.Now;
if (modelstate.isvalid)
{
Db. Zhengxings.add (zhengxing);
Db. SaveChanges ();
Return redirecttoaction ("Manageindex");
}
Else
Return View (zhengxing);
}

The zhengxing model has title,content,author,createdate,clickcount these fields, but in the Create page only assigns the title and Content, does not give author and createdate assignment, but in the background assignment, but each modelstate.isvalid is false, finally found the problem, as long as the model in the [Required (errormessage = "Author cannot be empty" )] Comment out the line.

Final Summary : The validation of Modelstate.isvalid is to validate the model before the action is invoked after the submit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.