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.