Asp.net MVC custom client verification (checkbox list verification)

Source: Internet
Author: User

Recently, when using MVC for development, it is quite convenient to use the client for input verification and the new view Engine Using mvc3. You don't have to write a lot of JS Code on your own, and the effect is acceptable.

However, when an external output such as a checkbox list is involved, the verification code has to be written on its own. As a result, the client adopts two sets of verification and it does not feel uniform or elegant, so I figured out the following implementation method.

The extension class of htmlhelper mainly includes methods such as checkboxlist and checkboxlistfor. With these methods, you can generate the checkbox list in this way.

@ Html. checkboxlistfor (M => M. rolelist, "Li ")

All the code is extended.

Htmlhelperextention. CS
Using system;
Using system. Collections. Generic;
Using system. LINQ. expressions;
Using system. text;
Using system. Web. MVC;

Namespace newborn. bscommon
{
/// <Summary>
/// Htmlhelper Extension
/// </Summary>
Public static class htmlhelperextention
{
Public static mvchtmlstring inputlist (this htmlhelper helper, ienumerable <selectlistitem> selectlist, string checkboxname, string splittagname, inputtype)
{
Return inputlist (helper, null, selectlist, checkboxname, splittagname, inputtype );
}

/// <Summary>
/// Generate the checkbox list
/// </Summary>
/// <Param name = "helper"> htmlhelper </param>
/// <Param name = "checkboxname"> name attribute </param>
/// <Param name = "splittagname"> outer layers of each selectlist </param>
/// <Param name = "inputtype"> inputtype </param>
/// <Param name = "selectlist"> selectlist </param>
/// <Param name = "metadata"> metadata </param>
/// <Returns> mvchtmlstring </returns>
Public static mvchtmlstring inputlist (this htmlhelper helper, modelmetadata metadata, ienumerable <selectlistitem> selectlist, string checkboxname, string splittagname, inputtype)
{
If (helper = NULL) throw new argumentnullexception ("helper ");
If (selectlist = NULL) throw new argumentnullexception ("selectlist ");
If (string. isnullorempty (checkboxname) throw new argumentnullexception ("checkboxname ");

Stringbuilder sb = new stringbuilder ();
Int idindex = 0;
Tagbuilder = new tagbuilder ("span ");
Foreach (selectlistitem item in selectlist)
{
Tagbuilder splittagbuilder = NULL;
If (! String. isnullorempty (splittagname ))
Splittagbuilder = new tagbuilder (splittagname );
Tagbuilder checktagbuilder = new tagbuilder ("input ");
Checktagbuilder. attributes ["type"] = inputtype. tostring ();
Checktagbuilder. attributes ["name"] = checkboxname;
Checktagbuilder. attributes ["value"] = item. value;

String checkboxid = checkboxname + "_ id _" + idindex;
Checktagbuilder. attributes ["ID"] = checkboxid;
If (item. Selected)
Checktagbuilder. attributes ["checked"] = "checked ";
Tagbuilder labeltagbuilder = new tagbuilder ("label") {innerhtml = helper. encode (item. Text )};

Labeltagbuilder. attributes ["for"] = checkboxid;
String checkhtml = checktagbuilder. tostring () + labeltagbuilder. tostring ();
If (splittagbuilder! = NULL)
{
Splittagbuilder. innerhtml + = checkhtml;
SB. appendline (splittagbuilder. tostring ());
}
Else
SB. appendline (checkhtml );

Idindex ++;
}

Tagbuilder hiddentagbuilder = new tagbuilder ("input ");
Hiddentagbuilder. attributes ["type"] = "hidden ";
Hiddentagbuilder. mergeattribute ("name", checkboxname );
Hiddentagbuilder. mergeattribute ("ID", "hidden" + checkboxname );
Hiddentagbuilder. mergeattributes <string, Object> (helper. getunobtrusivevalidationattributes (checkboxname, metadata ));
Tagbuilder. innerhtml = hiddentagbuilder + sb. tostring ();
Return mvchtmlstring. Create (tagbuilder. tostring ());
}
/// <Summary>
/// Generate the checkbox list
/// </Summary>
/// <Param name = "helper"> htmlhelper </param>
/// <Param name = "selectlist"> </param>
/// <Param name = "checkboxname"> name attribute </param>
/// <Returns> mvchtmlstring </returns>
Public static mvchtmlstring checkboxlist (this htmlhelper helper, ienumerable <selectlistitem> selectlist, string checkboxname)
{
Return helper. inputlist (selectlist, checkboxname, null, inputtype. checkbox );
}

Public static mvchtmlstring inputlistfor <tModel, tproperty> (this htmlhelper <tModel> htmlhelper, expression <func <tModel, tproperty> expression, string splittag, inputtype)
{
Modelmetadata = modelmetadata. fromlambdaexpression <tModel, tproperty> (expression, htmlhelper. viewdata );
List <selectlistitem> List = (list <selectlistitem>) modelmetadata. model );
Return htmlhelper. inputlist (modelmetadata, list, modelmetadata. propertyname, splittag, inputtype );
}
Public static mvchtmlstring checkboxlistfor <tModel, tproperty> (this htmlhelper <tModel> htmlhelper, expression <func <tModel, tproperty> expression)
{
Return htmlhelper. inputlistfor (expression, "span", inputtype. checkbox );
}
Public static mvchtmlstring checkboxlistfor <tModel, tproperty> (this htmlhelper <tModel> htmlhelper, expression <func <tModel, tproperty> expression, string splittag)
{
Return htmlhelper. inputlistfor (expression, splittag, inputtype. checkbox );
}

/// <Summary>
/// Generate the checkbox list
/// </Summary>
/// <Param name = "helper"> </param>
/// <Param name = "selectlist"> </param>
/// <Param name = "checkboxname"> </param>
/// <Param name = "splittagname"> tag name of each separator </param>
/// <Returns> </returns>
Public static mvchtmlstring checkboxlist (this htmlhelper helper, ienumerable <selectlistitem> selectlist, string checkboxname, string splittagname)
{
Return inputlist (helper, selectlist, checkboxname, splittagname, inputtype. checkbox );
}

 

Public static mvchtmlstring radioboxlistfor <tModel, tproperty> (this htmlhelper <tModel> htmlhelper, expression <func <tModel, tproperty> expression)
{
Return htmlhelper. inputlistfor (expression, "span", inputtype. Radio );
}

/// <Summary>
/// Generate the radiobutton list
/// </Summary>
/// <Param name = "helper"> </param>
/// <Param name = "selectlist"> </param>
/// <Param name = "checkboxname"> </param>
/// <Param name = "splittag"> </param>
/// <Returns> </returns>
Public static mvchtmlstring radiobuttonlist (this htmlhelper helper, ienumerable <selectlistitem> selectlist, string checkboxname, string splittag)
{
Return inputlist (helper, selectlist, checkboxname, splittag, inputtype. Radio );
}

/// <Summary>
/// Generate the radiobutton list
/// </Summary>
/// <Param name = "helper"> </param>
/// <Param name = "selectlist"> </param>
/// <Param name = "checkboxname"> </param>
/// <Returns> </returns>
Public static mvchtmlstring radiobuttonlist (this htmlhelper helper, ienumerable <selectlistitem> selectlist, string checkboxname)
{
Return inputlist (helper, selectlist, checkboxname, null, inputtype. Radio );
}
}
}
The following JS file must be referenced because it is verified on the client.

Script Section

<SCRIPT src = "@ URL. Content ("~ /Scripts/jquery-1.4.4.min.js ")" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "@ URL. Content ("~ /Scripts/jquery. Validate. Min. js ")" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "@ URL. Content ("~ /Scripts/jquery. Validate. unobtrusive. Min. js ")" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "@ URL. Content ("~ /Scripts/custom/jquery. Validate. unobtrusive. extension. js ")" type = "text/JavaScript"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
$ (Function (){
New checkboxlist ("rolelist", "hiddenrolelist"); // initial verification
});
</SCRIPT>
Write this sentence on the page

$ (Function (){
New checkboxlist ("rolelist", "hiddenrolelist"); // initial verification

});

It is to let the script bind events, there may be a better way, this is to be studied.

The Code on the page is as follows:

HTML section

<Div class = "select">
@ Html. checkboxlistfor (M => M. rolelist, "Li ")
@ Html. validationmessagefor (M => M. rolelist)
</Div>
Listslectrangeattribute. CS File

View code
Using system;
Using system. Collections. Generic;
Using system. componentmodel. dataannotations;
Using system. Web. MVC;

Namespace newborn. bscommon
{
[Attributeusage (attributetargets. Property | attributetargets. FIELD | attributetargets. parameter, allowmultiple = false)]
Public class listslectrangeattribute: validationattribute, iclientvalidatable
{
Private const string errformat = "The minimum option for this item is {0} and the maximum option is {1 }";

Public listslectrangeattribute ()
{
Minselected = 0;
Maxselected =-1;
}

Public int minselected {Get; set ;}

Public int maxselected {Get; set ;}

Public override bool isvalid (object value)
{
Return true;
}

Public override string formaterrormessage (string name)
{
Return string. Format (errformat, minselected> 0? Minselected. tostring (): "unlimited", maxselected> 0? Maxselected. tostring (): "unlimited ");
}

Public ienumerable <modelclientvalidationrule> getclientvalidationrules (modelmetadata metadata, controllercontext context)
{
Modelclientvalidationrule rule = new modelclientvalidationrule
{
Validationtype = "list ",
Errormessage = formaterrormessage (metadata. getdisplayname ())
};
Rule. validationparameters ["min"] = minselected;
Rule. validationparameters ["Max"] = maxselected;

Yield return rule;
}
}
}
Jquery. validate. unobtrusive. extension. the JS file mainly verifies the checkbox list on the client side, such as the checkbox list. Careful friends will find that because the checkbox list contains multiple inputs, I didn't do it based on it, instead, a hidden domain is used to record the number of items currently selected (currently, only the number of items selected is recorded, and the selected item value is not recorded. However, this type of requirement is not currently available, it can be easily expanded ).
// By xianhong
// Add verification. For example, You must select a certain number of verification items in the verification box.
$. Validator. addmethod ("maxminselected", function (value, element, Param ){
VaR min = Param [0];
VaR max = Param [1];
If (value> = min & (max <= 0 | value <= max ))
Return true;
Return false;
});
$. Validator. unobtrusive. adapters. addminmax ("list", "min", "Max", "maxminselected ");

VaR checkboxlist = function (name/* input name attribute */, hiddenid/* hidden field selected for record */){
This. checkedcount = function (){
VaR selected = $ ("input [name = '" + name + "']: checked ");
Return selected. length;
};
This. All = function (){
Return $ ("input [name = '" + name + "']");
};
This. bindclick = function (){
VaR thisobj = this;
This. All (). Click (function (){
$ ("#" + Hiddenid). Val (thisobj. checkedcount ());
});
};
This. bindclick ();
};

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.