ASP. net mvc Case Study (5)

Source: Internet
Author: User
Tags jquery library

Data Verification

In the previous article, we completed the announcement publishing function. However, from the perspective of robustness, this function is not perfect, because the data we input must meet certain constraints. For example, in our example, at least we cannot use an empty string as the title or content. Next, we will add the data verification function for the program,

ASP. net mvc provides good data verification implementation support. Let's take a look at the implementation process. First, modify the release. aspx view. The modified view is as follows.

Release. aspx:

<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "release. aspx. CS "inherits =" mvcdemo. views. announce. release "%> <% @ import namespace =" mvcdemo. models. entities "%> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" ""> <HTML xmlns = ""> 

We can see that there are no major changes, but there are two more HTML. validationmessage methods. It can be understood that this method is equivalent to generating a span tag, and this span is the place where the error message is to be displayed. This method receives a parameter to specify its name in the controller. If you are confused about this, it doesn't matter. After reading the Controller code, you will understand everything.

Announcecontroller. CS:

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using system. web. MVC. ajax; using mvcdemo. models; using mvcdemo. models. interfaces; using mvcdemo. models. entities; namespace mvcdemo. controllers {public class announcecontroller: controller {public actionresult release () {icategoryservice cserv = servicebuilder. buildcategoryservice (); List Categories = CSER V. getall (); viewdata ["categories"] = new selectlist (categories, "ID", "name"); Return view ("release");} public actionresult dorelease () {If (string. isnullorempty (request. form ["title"]) | string. isnullorempty (request. form ["content"]) {If (string. isnullorempty (request. form ["title"]) {viewdata. modelstate. addmodelerror ("titlevalidator", "The announcement title cannot be blank! ");} If (string. isnullorempty (request. Form [" content "]) {viewdata. modelstate. addmodelerror (" contentvalidator "," The announcement content cannot be blank! ");} Return release ();} announceinfo announce = new announceinfo () {id = 1, Title = request. form ["title"], Category = int32.parse (request. form ["category"]), content = request. form ["content"],}; iannounceservice aserv = servicebuilder. buildannounceservice (); aserv. release (announce); viewdata ["announce"] = announce; return view ("releasesucceed ");}}}

We can see that our dorelease action method has many more things. What are we looking at? When the title or content passed from the form is empty, we do some processing. Note that this viewdata. modelstate. addmodelerror method, which is the HTML method we just mentioned. the error message method is added to the span generated by validationmessage. It can have two parameters. The first one specifies the span, which is the HTML parameter. parameters in validationmessage correspond. The second parameter is the information to be displayed.

I believe that the combination of views and controllers is well understood. Finally, if the title or content has a null value, we will not call the business logic component for processing, but call the release action. Why don't we use redirect? Because we need to keep the data in viewdata, the error information we just put in it, and the Redirect is used, the viewdata information cannot be passed.

Now let's release the announcement. If we intentionally leave nothing blank, submit it and check the result:

No problem. Our program has successfully completed the integrity check on the title and content (Here we cannot leave it blank). When the verification fails, the release announcement view is returned, and the error message is displayed correctly.

Maybe you have a question: Why is no error message displayed when you first request the release view? Because modelerror in viewdata is empty at that time. The tag generated by HTML. validationmessage will automatically search for error messages with the same name in modelerror. It cannot be found. Of course, it is empty. When empty information is submitted, the dorelease action adds content to the modelerror of viewdata. Therefore, when the release view is returned again, the corresponding information is displayed at the specified position.

Use ASP. NET ajax to verify client data

The above code runs well and meets our requirements. However, it should be done on the client to verify whether the title content is null. Of course, in order to place malicious attacks or shield JavaScript from the browser, we should verify it in the background, but we cannot send such requests to the background for verification every time, which is too resource-consuming, after all, there are only a few browsers that are blocked by malicious attackers and JavaScript. Therefore, we should verify the data before it is sent to the backend, which can save a lot of resources.

Next, we use the ASP. NET Ajax framework to complete client data verification.

To be honest, in ASP. net MVC using ASP. net Ajax or jquery is too convenient. Do not believe you expand the scripts folder. If you see no, Microsoft has put these libraries in it. So, all we need to do is directly reference them. Check the Modified Release. aspx.

Release. aspx:

<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "release. aspx. CS "inherits =" mvcdemo. views. announce. release "%> <% @ import namespace =" mvcdemo. models. entities "%> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" ""> <HTML xmlns = ""> 

There are two changes. First, we reference two JS files in the page header. The first one is ASP.. Net Ajax library file. The second one is the JS file that we will implement later. You may have noticed the URL. content. The URL is an object of viewpage, and the most common method is content. Its function is to return the path of a file. In general, Asp. net MVC, the directory structure becomes a bit strange, such as JS, CSS, images, and other places related to path (even relative paths) references may have problems, however, as long as you use URLs in these places. content to generate a path, rather than writing the path directly in the page. Generally, there is no problem. Therefore, if Javascript, CSS, and images are referenced, use URL. content to generate a path. There is only one parameter, that is, the original relative path of the file.

The next change is that the span that displays the error message is not generated by HTML. validationmessage, but a normal span.

In the scripts directory, create the microsoftajaxvalidate. js file.

Microsoftajaxvalidate. JS:

SYS. application. add_init (onpageinit); function onpageinit () {$ addhandler ($ get ("Submit"), "click", validate);} function validate () {if ($ get ("title "). value = "" | $ get ("content "). value = "") {if ($ get ("title "). value = "") {$ get ("titlevalidator "). innerhtml = "title cannot be blank! ";} If ($ get (" content "). value =" ") {$ get (" contentvalidator "). innerhtml =" content cannot be blank! ";} Return false;} return true ;}

I will not talk about this code. If you are interested in ASP. NET Ajax, refer to the ASP. NET Ajax client programming journey series.

Run now, leave the title and content blank, and submit. OK! The effect is similar to that of the previous one, but this time it was verified on the client and not submitted to the server.

Integrate jquery

Next we will use jquery to implement this function.

Actually, after reading the above implementation, I think you have come up with how to integrate jquery. It is nothing more than introducing the corresponding library and JS files, and then writing verification code using jquery. The modified release. aspx does not need to be read. It is nothing more than introducing the jquery library under the scripts directory, and then introducing a custom validation JS file. Let's call it jqueryvalidate. js.

The following code creates jqueryvalidate. js in the scripts directory:

Jqueryvalidate. JS:

$ (Document ). ready (function () {$ ("# submit "). click (function () {if ($ ("# title "). ATTR ("value") = "" | $ ("# Content "). ATTR ("value") = "") {if ($ ("# title "). ATTR ("value") = "") {$ ("# titlevalidator "). ATTR ("innerhtml", "title cannot be blank! ");} If ($ (" # Content "). ATTR ("value") = "") {$ ("# contentvalidator "). ATTR ("innerhtml", "content cannot be blank! ");} Return false;} return true ;});});


From this article, we can see that the integration of Ajax in the MVC framework is not much different from that of common applications. The only difference is that when referencing external JS, you should use the URL. content method to process the relative path. In fact, we didn't use Ajax in this article, but only integrated javascirpt, but this is enough, because Ajax is nothing more than including asynchronous background calls in these JavaScript.

In fact, ASP. net mvc has a special extension for ASP. NET Ajax, which is placed in microsoftmvcajax. js. In viewpage, there is an ajaxhelper object called Ajax, which can implement some simple asynchronous calls. However, this extension function is very limited. If you are interested, you can study it yourself. I personally suggest you write your own JS Code. Of course, you can use an excellent framework like ASP. NET Ajax or jqeury.

This article is here first. In the next article, we will discuss the use of interceptor.

This article is from Zhang Yang's blog T2's notebook

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: 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.