Implementation of object member data binding under ASP.net

Source: Internet
Author: User
Tags definition bind bool cas
Asp.net| Object | data

Friends who have used monorail should know that it provides the object member data binding function is very convenient, by marking parameter properties or methods can automatically bind the data submitted back and object members; With these handy features, you can actually save a lot of set code. However, these features are only provided by the monorail, so the implementation of similar functions to facilitate their own development.

To achieve the goal: flexible and easy to implement data binding.

Ordersearch search = formcontext.bindobject<ordersearch> ();
Orders order = formcontext.bindobject<orders> (' order ');

Make rules and constraints

First, you determine the mapping relationship of the data and member properties of the Web submission, which you can use by name conventions:

<input id= "Text1" Name= "CompanyName" type= "text"/>

Xxxx. LastName, Xxxx_lastname, or Xxxxlastname. A prefix can be specified in the binding process to bind an object member, but the WebForm control's name is asp.net generated and is relatively complex in relational analysis.

Definition of type conversion interface

Because the situation of conversion is difficult to determine; NET, there are other transformations in the actual application, such as: Httppostedfile to byte[], serialization of string to object, and so on. Therefore, the development of the transformation interface can facilitate the implementation of scalable and configurable.

public interface Istringconverter
{
Object ConvertTo (string value, out bool succeeded);
}

Since most of the data provided by the Web is provided in string, a description based on a string transformation is defined. The interface based reality is also simple:

public class Tosbyte:istringconverter
{
#region Istringconverter Members
Object Istringconverter.convertto (string value, out bool succeeded)
{
SByte Nvalue;
succeeded = sbyte. TryParse (value, out nvalue);
return nvalue;
}
#endregion
}

The realization of Istringconverter factory

Because of the uncertainty of the conversion situation, the way to the factory to achieve the external closure of the code and good scalability. You can get the relevant transformation instance through the target type, and IDictionary in. NET to meet the requirements of the application.

Static Idictionary<type, istringconverter> mconverters;
public static Idictionary<type, istringconverter> converters
{
Get
{
if (mconverters = null)
{
Lock (typeof (Converterfactory))
{
OnInit ();
}
}
return mconverters;
}
}
static void OnInit ()
{
if (mconverters!= null)
Return
Mconverters = new Dictionary<type, istringconverter> ();
Mconverters.add (typeof (Byte), New ToByte ());
Loadconfig ();
}
Load the converter mappings from the configuration file and replace the original converter if the same type of converters exist
static void Loadconfig ()
{
Load Config
<converter type= "System.Int32", value= "HFSoft.Binder.ToByte"
}

For ease of use, the internal base type can be hard-coded in the factory, because of the uncertainty of the conversion, allowing for the introduction of a different case type converter through the configuration file.

Custom attributes that can be extended

Although the factory can achieve the configuration of the transformation interface, it is difficult to meet the application requirements, in some cases the type converter is only valid in some object members (although the configuration file can also meet the period requirements, but it is not a good choice to define such a small granularity in the configuration file) To specify a type converter for the relevant property by attribute.

<summary>
Converters for specific members of an object in special cases
</summary>
[AttributeUsage (Attributetargets.property)]
public class Converterattribute:attribute, Istringconverter
{
Public Converterattribute (Type convertertype)
{
Mconvertertype = Convertertype;
}
Public Converterattribute (Type convertertype, String defvalue)
{
Mconvertertype = Convertertype;
Mdefaultvalue = Defvalue;
}
Private Type Mconvertertype;
Public Type Convertertype
{
Get
{
return mconvertertype;
}
}

        private String mdefaultvalue;
        public String defaultvalue
         {
            get
             {
                 return mdefaultvalue;
           }
            Set
             {
                 Mdefaultvalue = value;
           }
       }

Protected Istringconverter CreateInstance ()
{
if (Mconverters.containskey (Convertertype))
return Mconverters[convertertype];
Lock (typeof (Converterattribute))
{
if (!mconverters.containskey (Convertertype))
{
Mconverters.add (Convertertype, (istringconverter) activator.createinstance (Convertertype));
}
return Mconverters[convertertype];
}
}
Static Idictionary<type, istringconverter> mconverters = new Dictionary<type, istringconverter> ();
#region Istringconverter Members
public Object ConvertTo (string value, out bool succeeded)
{
String newvalue = value!= null? Value:defaultvalue;
Return CreateInstance (). ConvertTo (NewValue, out succeeded);
}
#endregion
}

Converterattribute can facilitate the development of a smaller size configuration

Private byte[] Mfilestream;
[Converter (typeof (Filestreamconverter), "Iconphoto")]
Public byte[] FileStream
{
Get
{
return mfilestream;
}
Set
{
Mfilestream = value;
}
}

The above definition can be uploaded file flow into byte[] into the FileStream attribute.

Functional Integration Implementation
Now integrate everything together to meet the requirements of the purpose.

public Object Bind (System.Collections.Specialized.NameValueCollection values, string prefix)
{
Object newobj = Activator.CreateInstance (ObjectType);

if (prefix = null)

prefix = "";

Object value;

foreach (PropertyInfo item in Properties)
{
Value = Values[prefix + "." + Item. Name];
if (value = = null)
Value = Values[prefix + "_" + item. Name];
if (value = = null)
Value = Values[prefix + item. Name];
BindProperty (newobj, item, (string) value);
}
return newobj;
}

private void BindProperty (Object obj, PropertyInfo property, String value)
{
Istringconverter Stringconver;
Object Nvalue;
bool confirm = false;
Object[] cas = property. GetCustomAttributes (typeof (Converterattribute), true);
if (CAs. Length > 0)
{
Nvalue = ((Converterattribute) cas[0]). ConvertTo (value, out confirm);
if (confirm)
Mpropertieshandle[property]. SetValue (obj, nvalue);
}
Else
{
If (property, ConverterFactory.Converters.ContainsKey. PropertyType))
{
Stringconver = Converterfactory.converters[property. PropertyType];
Nvalue = Stringconver. ConvertTo (value, out confirm);
if (confirm)
Mpropertieshandle[property]. SetValue (obj, nvalue);
}
}
}

Because the data submitted by the Web can be obtained almost by httprequest.params, it is only necessary to match the search based on the attribute name and the relevant prefix. Here the implementation of the matching method is not ideal, in fact, can be in the relevant page of the first request can be analyzed to the relationship exists in IDictionary, later use directly on it.

The above function is to write an MVC component of the data binding function, in fact, can completely transplant the traditional webform work; friends with better ideas please submit more comments.



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.