Let's do something cool: Use dojo to make your own. Net MVC control index & writing plan

Source: Internet
Author: User

I replaced my recent mantra with: This will be cooooooooooooooooooool, very cooooooooooooooooool. So the name of this blog is so strange.

I plan to write this into a series and share with you some cool functions, effects, ideas, and so on.

 

I always think that the best way for programmers to communicate is through code. We strongly recommend that you read this article with the code

Source code download: Click here to download the source code

The page effect is as follows: Click here to download HTML (the file is very small. We suggest you download it all to see the effect. The first loading will be slow, because both JS and CSS files are obtained from Google)

My blog index: Index & writing plan

 

First, we will introduce dojo. Jquery is a lightweight JS library, while dojo is a heavy JS library. Compared with jquery, Dojo performs better in OOP and is more suitable for large-scale applications.

Literacy Stickers: http://www.mhtml5.com/2012/06/5174.html

 

Body start:

A model is provided. This model is very simple. There is only one string, and there is a regular attribute:

public class Test{        [RegularExpression(@"[\\w]+", ErrorMessage = "Invalid Non-Space Text.")]        public string b { get; set; }    }

A friend who has used razor is familiar with this Code:

@model Test@Html.TextBoxFor(o=>o.b)

This outputs the following HTML code to the page:

<input data-val="true" data-val-regex="Invalid Non-Space Text." data-val-regex-pattern="[\\w]+" id="b" name="b" type="text" value="String with Space">

As you can see,. Net MVC intelligently reflects the attribute on Attribute B and generates a regular expression verification for us.

However, there are two problems:

1. This regular expression verification is not very nice, and will only be triggered when the form is submitted, rather than triggered when the focus is left.

2. If I want to use jquery to add an onmousemove event for this Textbox, add the following code:

<script>    $(document).ready(function () {        $("#b").mousemove(function () {            alert(1);        })    })</script>

This will add a mousemove event for the textbox.

However, writing like this is not cool at all. Compared to capturing controls using jquery and binding events, I prefer to bind JS events when writing controls. In other words, I want to write the following code:

<script>    function show(str) {        alert(str);    }</script><input data-val="true" data-val-regex="Invalid Non-Space Text." data-val-regex-pattern="[\\w]+" id="b" name="b" type="text" value="" onmousemove="show(this.value);">

 

So I want this effect: use this model

        public class Test        {            [Required]            public DateTime a { get; set; }            [RegularExpression(@"[\\w]+", ErrorMessage = "Invalid Non-Space Text.")]            public string b { get; set; }            [Required]            [Range(1, 11111)]            public int c { get; set; }            public List<Test> d { get; set; }            public bool e { get; set; }        }

Add the following code to cshtml:

@model Test<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dijit/themes/claro/claro.css" media="screen" /><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js" djconfig="parseOnLoad: true"></script><script>    function show(str) {        alert(str);    }</script><body class="claro">        @Html.MyDateTextBoxFor(o => o.a).ToHtml()        @Html.MyTimeTextBox(o => o.a).ToHtml()        @Html.MyTextBoxFor(o => o.b).OnBlur("show(this.value)").ToHtml()        @Html.MyTextBoxFor(o => o.c).ToHtml()        @Html.MyDropDownListFor(o => o.c, a => a.b, a => a.c.ToString(), Model.d).OnChange("show(this.value)").ToHtml()        @Html.MyButton("Submit", true).ToHtml()        @Html.MyMultiSelectFor(o => o.c, a => a.b, a => a.c.ToString(), Model.d).OnClick("show(this.value)").ToHtml()        @Html.MyCheckBoxFor(o => o.e).ToHtml()</body>

The generated page is as follows: Click here to download HTML (the file is small. We recommend that you download it to see the effect)

The first loading of the above link will be slow, because both JS and CSS files are obtained from Google.

To achieve this, we need to rewrite the. net mvc control code.

The following uses dropdownlist and multiselect as examples to explain the code

// ================================================ = // Create by jinn 2012.12.10 only supports mydropdownlistfor and mymultiselectfor, commented out the version without, complete the note at the bottom of // edit by /// ================================== ============ using system. collections. generic; using system. LINQ. expressions; using system. text; namespace system. web. MVC {public static class myselectextensions {public static tagbuilder mydropdownlistfor <tModel, tproperty> (This html Helper <tModel> htmlhelper, expression <func <tModel, tproperty> expression, func <tModel, string> textfield, func <tModel, string> valuefield, ilist <tModel> selectlist) {modelmetadata metadata = modelmetadata. fromlambdaexpression (expression, htmlhelper. viewdata); string name = expressionhelper. getexpressiontext (expression); Return selecthelper <tModel, tproperty> (htmlhelper, name, textfield, valuefie LD, selectlist, metadata, selecttype. dropdownlist);} public static tagbuilder mymultiselectfor <tModel, tproperty> (this htmlhelper <tModel> htmlhelper, expression <func <tModel, tproperty> expression, func <tModel, string> textfield, func <tModel, string> valuefield, ilist <tModel> selectlist) {modelmetadata metadata = modelmetadata. fromlambdaexpression (expression, htmlhelper. viewdata); string name = E Xpressionhelper. getexpressiontext (expression); Return selecthelper <tModel, tproperty> (htmlhelper, name, textfield, valuefield, selectlist, metadata, selecttype. multiselect);} Private Static tagbuilder selecthelper <tModel, tproperty> (this htmlhelper <tModel> htmlhelper, string name, func <tModel, string> textfield/* display */, func <tModel, string> valuefield/* value */, ilist <tModel> selectlist/* Data Source */, modelm Etadata metadata/* metadata */, selecttype tpye) {string fullname = htmlhelper. viewbag. ID; string id = fullname + "_" + name; stringbuilder sb = new stringbuilder (); If (selectlist! = NULL) {foreach (VAR item in selectlist) {tagbuilder tag = new tagbuilder ("option"); tag. mergeattribute ("value", valuefield (item); string selectedvalue = valuefield (item); If (selectedvalue = convert. tostring (metadata. model) {tag. mergeattribute ("selected", "selected");} tag. setinnertext (textfield (item); sb. appendline (tag. tostring (tagrendermode. normal) ;}} tagbuilder = new tagbuilder ("select") {innerhtml = sb. tostring ()}; Switch (tpye) {Case selecttype. dropdownlist: tagbuilder. mergeattribute ("data-Dojo-type", "dijit/form/filteringselect"); break; Case selecttype. multiselect: tagbuilder. mergeattribute ("data-Dojo-type", "dijit/form/multiselect"); break; default: tagbuilder. mergeattribute ("data-Dojo-type", "dijit/form/filteringselect"); break;} tagbuilder. mergeattribute ("name", name, true); tagbuilder. generateid (ID); Return tagbuilder;} public Enum selecttype {dropdownlist = 1, multiselect = 2 ,}}}

In. Net MVC, the return type of the control is mvchtmlstring, but it is not convenient to add JS events. So here I change all the return types to tagbuilder. After all the events are added, convert them to mvchtmlstring using the tohtml method.

The code for adding a JS event is as follows:

// ================================================ = // Create by jinn 2012.12.5 basic version, five common events, such as onclick and onblur, have been completed. // I know these five events can be written together, but in order to be extensible and with as few Page code as possible, I have chosen this writing method // EDIT BY. Please complete this annotation // ============================ =============== namespace system. web. MVC {public static class function {public static tagbuilder onclick (this tagbuilder, string functionname) {tagbuilder. mergeattribute ("onclick", functionname); Return tagbuilder;} public static tagbuilder onmousemove (this tagbuilder, string functionname) {tagbuilder. mergeattribute ("onmousemove", functionname); Return tagbuilder;} public static tagbuilder onfocus (this tagbuilder, string functionname) {tagbuilder. mergeattribute ("onfocus", functionname); Return tagbuilder;} public static tagbuilder onchange (this tagbuilder, string functionname) {tagbuilder. mergeattribute ("onchange", functionname); Return tagbuilder;} public static tagbuilder onblur (this tagbuilder, string functionname) {tagbuilder. mergeattribute ("onblur", functionname); Return tagbuilder ;} // both Auto-closing and default close and sum can be parsed. // For example, <ASD/> and <ASD> </ASD> are the same. // The default closed format is used here // by jinn 2012.12.8 /// <summary> // default close and Sum Method /// </Summary> Public static mvchtmlstring tohtml (this tagbuilder) {return New mvchtmlstring (tagbuilder. tostring (tagrendermode. normal ));}}}

 

In this case, add

@ HTML. mydropdownlistfor (O => O. c, A =>. b, A =>. c. tostring (), model. d ). onchange ("show (this. value )"). tohtml ()

You can generate a coooooooooooooooooool dropdownlist control.

 

Put aside

 

PS: to be lazy, all the namespaces of my controls are system. Web. MVC.

PS: the code coloring function of the blog garden seems to be suspended. Click backspace to remove all the colors in the 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.