ViewData has a Modelstate property, which is a collection of dictionaries of type Modelstate type Modelstatedictionary. This property is useful when validating data. When using Html.validationmessage (), it is from the viewdata.modelstate to detect whether there is a specified key, if present, the error message is prompted. For example, in the previous article, Introduction to ASP. NET MVC 7, Hellper and the Updatemodel method used in the submission and binding of data:
We use Html.validationmessage (string modelname) in view to validate the specified property:
Html.validationmessage () has several overloads:
where ValidationSummary () is used to display all of the validation information. Similar to the ValidationSummary validation controls inside ASP.
Let's test the/admin/setting page:
When using the Updatemodel method to update the BlogSettings.Instance.PostsPerPage, when we fill in "10d", because the postsperpage is integral type, so the Updatemodel method will be wrong, A corresponding error message is added to the viewdata.modelstate, so the Html.validationmessage () method can detect and prompt for errors from the viewdata.modelstate. The Html.validationmessage () method adds a CSS class named "Input-validation-error" to the input box for the property that is faulted, while the CSS class with the following hint information is named " Field-validation-error ":
The style of CSS classes can be defined freely by ourselves. Highlighted in red.
OK, let's make the new essay function. Let's start by writing a form page that provides the user input of the essay content:
<p>
<label for= "title" > title </label>
<%=html.textbox ("title", new {id = "title", @class = "Required"})%>
<%=html.validationmessage ("Title")%>
</p>
<p>
<label for= "Content" > Contents </label>
<%=html.textarea ("Content")%>
<%=html.validationmessage ("Content")%>
</p>
<p>
<label for= "Slug" >url address alias (if empty, same name as title) </label>
<%=html.textbox ("Slug", new {id = "Slug", @class = "Required"})%>
<%=html.validationmessage ("Slug")%>
</p>
Then we save the data submitted by the User:
[Acceptverbs ("POST"), ActionName ("Newpost")]
Public ActionResult savenewpost (formcollection form)
{
Post post = new post ();
Try
{
Updatemodel (post, new[] {"Title", "Content", "Slug"});
}
Catch
{
Return View (POST);
}
Post. Save ();
Return ShowMsg (New list<string> () {"Post a successful essay"});
}
Since these three values are string types, Updatemodel is not an error if the value is null, and our title and content are not allowed to be empty, or we think our slug cannot be longer than 100, that is, we need our own business rules. This is where we might write:
Try
{
Updatemodel (post, new[] {"Title", "Content", "Slug"});
}
Catch
{
Return View (POST);
}
if (string. IsNullOrEmpty (post. Title))
{
ViewData.ModelState.AddModelError ("Title", post.) Title, "caption cannot be empty");
}
if (string. IsNullOrEmpty (post. Content))
{
ViewData.ModelState.AddModelError ("Content", post.) Content, "Contents cannot be empty");
}
if (! ViewData.ModelState.IsValid)
{
Return View (POST);
}
Viewdata.modelstate provides a Addmodelerror method that allows us to add information about validation failures. We can do the business rule validation of the object as in the code, but once the business rules are many, the code is spectacular and not well controlled. So how do we better validate the business rules? With a good architecture of blogengine.net, we can do this easily.
First, let's change the code inside the Blogengine.core businessbase. As we said earlier, Businessbase implements the IDataErrorInfo interface, which has an indexer that causes the Viewdata.eval () method call to return String.Empty when searching for the value of the indexer and to make Viewdata.eval () It is considered that the value has been found, thereby invalidating.
We can return a string. Empty is modified to return NULL. But we don't need to use this interface here, so we remove the interface and annotate the corresponding code. Then we expose a Brokenrules property that returns all the current destructive business rules (the Red-box section code adds to us):
Businessbase provides an abstract Validationrules method for adding validation rules to a business class override this method (see Businessbase Validation section for details).
Validation
We override this method in the Post class to add validation rules:
We can then write our code elegantly in the Controller's action to validate the business rules:
[Acceptverbs ("POST"), ActionName ("Newpost")]
Public ActionResult savenewpost (formcollection form)
{
Post post = new post ();
Try
{
Updatemodel (post, new[] {"Title", "Content", "Slug"});
}
Catch
{
Return View (POST);
}
if (!post. IsValid)
{
foreach (String key in post.) Brokenrules.keys)
{
ViewData.ModelState.AddModelError (Key, Form[key], post. Brokenrules[key]);
}
Return View (POST);
}
Post. Save ();
Return ShowMsg (New list<string> () {"Post a successful essay"});
}
We notice that a formcollection parameter is used in the action above, and the system automatically assigns all the form values (Request.Form) submitted by the form to it. Client-side validation can be used with jquery's validation plug-in, which is not verbose here.
Write so much for the time being, and think about what to add. enjoy! Post by Q.lee.lulu.
This article's blog Program Sample code: 4mvcblog_8.rar
Go Introduction to ASP. 8, Modelstate and data validation