ASP. net mvc Practice Series 3-server-side data verification

Source: Internet
Author: User

Here we will mainly explain the data verification on the server side in ASP. net mvc. As for client verification, we will talk about it in future series.

There is a ModelState attribute in the Controller. This is a set of ModelState dictionaries of the ModelStateDictionary type. This attribute is useful for data verification. When Html. ValidationMessage () is used, it checks whether a specified KEY exists from ModelState. If yes, an error message is displayed.

1. Basic instance

Add the following file to View:

<% = Html. ValidationSummary ("Edit was unsuccessful. Please correct the errors and try again.") %>
<% Using (Html. BeginForm () {%>
<Fieldset>
<Legend> Fields </legend>
<P>
<Label for = "id"> id: </label>
<% = Html. TextBox ("id", Model. id) %>
<% = Html. ValidationMessage ("id", "*") %>
</P>
<P>
<Label for = "Title"> Title: </label>
<% = Html. TextBox ("Title", Model. Title) %>
<% = Html. ValidationMessage ("Title", "*") %>
</P>
<P>
<Input type = "submit" value = "Save"/>
</P>
</Fieldset>

<% }%>
Add the following code to the corresponding Controller:

Public ActionResult NewsEdit (int id)
{
NewsDataDataContext dc = new NewsDataDataContext ();
Return View (dc. News. First (n => n. id = id ));
}
[AcceptVerbs (HttpVerbs. Post)]
Public ActionResult NewsEdit (int id, FormCollection formValues)
{
News news = new News ();
UpdateModel (news );
If (String. IsNullOrEmpty (news. Title ))
{
ModelState. AddModelError ("Title", "Title cannot be blank ");
}
Else
{
// Update
}
Return View (news );
}
Use Html. validationMessage (string modelName) is used to verify the specified attribute. Here, the default convention in mvc is still used. If the content of modelName is the same as the key value in ModelState, it is displayed.

ValidationSummary () is used to display all verification information. It is similar to the ValidationSummary verification control in ASP. NET.

The result of running the program is:

Html. the ValidationMessage () method adds a CSS class named "input-validation-error" to the input box of the error attribute, at the same time, the CSS class name for the prompt information is "field-validation-error ":

<Input class = "input-validation-error" id = "Title" name = "Title" type = "text" value = ""/>
<Span class = "field-validation-error"> * </span>

CSS styles can be freely defined by ourselves.

2. Application

Here we add server-side verification for the previous News instance. First, we need a class to pass the error message.

Public class RuleViolation
{
Public string ErrorMessage {get; private set ;}
Public string PropertyName {get; private set ;}
Public RuleViolation (string errorMessage)
{
ErrorMessage = errorMessage;
}
Public RuleViolation (string errorMessage, string propertyName)
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}
Add a partial class for the News class in dbml to verify the attribute.

Public partial class News
{
Public bool IsValid
{
Get {return (GetRuleViolations (). Count () = 0 );}
}

Partial void OnValidate (ChangeAction action)
{
If (! IsValid)
Throw new ApplicationException ("Rule violations prevent saving ");
}
Public IEnumerable <RuleViolation> GetRuleViolations ()
{
If (String. IsNullOrEmpty (Title ))
Yield return new RuleViolation ("the Title must be entered", "Title ");
If (String. IsNullOrEmpty (Author ))
Yield return new RuleViolation ("The Author must be input", "Author ");

Yield break;
}
}
Enter the following code in Controller:

[AcceptVerbs (HttpVerbs. Post)]
Public ActionResult NewsEdit (int id, FormCollection formValues)
{
NewsDataDataContext dc = new NewsDataDataContext ();
News news = dc. News. First (n => n. id = id );
Try
{
UpdateModel (news );
Dc. SubmitChanges ();
Return RedirectToAction ("Details", new {id = id });
}
Catch (Exception)
{
Foreach (var issue in news. GetRuleViolations ())
{
ModelState. AddModelError (issue. PropertyName, issue. ErrorMessage );
}
Return View (news );
}
}
Note: When the SubmitChanges method is executed on datacontext, The OnValidate distribution method is triggered.

3. Source Code

4. Reference: Professional ASP. net mvc 1.0

Article from: http://www.cnblogs.com/nuaalfm/

Related Article

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.