Implement Form form field values in ASP.NET to automatically populate the operation model

  • 2021-06-28 12:18:19
  • OfStack

We know that one of the great things about ASP.NET MVC is that when Form forms are submitted to action, Form parameters can be directly assembled into action's parameter entity objects.

such as


action Method Register(UserModel userModel) {    .............................   }

When submitting the form, the fields inside the form are automatically encapsulated in the corresponding UserModel fields

So can WebForm also be purple?

Because data is acquired every time, good programmers should learn to encapsulate code, reuse code, and do no duplicate work

We can actually use reflection to instantiate objects (auto-assembly)

Well, there's not much rubbish...

pageload is simple


protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPost())
            {
                InitPage();// No. 1 Second Visit Rendering Page
            }
            else
            {
                UserModel userModel = AssembleModel<UserModel>(base.valueCollection);
            }
        }

The key is the AssembleModel method inside the base class

Inside base class

First we get the context parameter IT404


protected NameValueCollection valueCollection = HttpContext.Current.Request.Params;

The base class is simple in that it stores context-submitted parameters in valueCollection

Then look at the AssembleModel method, which is a generic method


/// <summary>
        /// Reflection Gets Properties of Class
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected PropertyInfo[] GetPropertyInfoArray(Type type)
        {
            PropertyInfo[] props = null;
            try
            {
                object obj = Activator.CreateInstance(type);
                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            catch (Exception ex)
            {             }
            return props;
        }         /// <summary>
        /// according to NameValueCollection automatic assembly
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="valueCollection"></param>
        /// <returns></returns>
        protected T AssembleModel<T>(NameValueCollection valueCollection)
        {
            PropertyInfo[] propertyInfoList = GetPropertyInfoArray(typeof(T));
            object obj = Activator.CreateInstance(typeof(T), null);// Create an instance of the specified type
            foreach (string key in valueCollection.Keys)// Values for all contexts
            {
                foreach (var PropertyInfo in propertyInfoList)// All entity attributes
                {
                    if (key.ToLower() == PropertyInfo.Name.ToLower())
                    {
                        PropertyInfo.SetValue(obj, valueCollection[key], null);// Assigning values to objects
                    }
                }
            }
            return (T)obj;
        }

Simply iterate through the parameters, then use reflection to iterate through the common attributes of the entity class, then match and assign values based on the name name

So in the future, we only need one sentence of code to automatically assemble the values saved from the client


UserModel userModel = AssembleModel<UserModel>(base.valueCollection);


Related articles: