The implementation code for assigning entity class objects to forms in asp.net
- 2020-05-12 02:26:38
- OfStack
There is a problem is: the form name and the object property name (I am the property assignment you can also use the field) to maintain 1, a little insecure, but the background is good, in the form data filling in the background to use more
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Gets form values through object Settings
/// </summary>
namespace Com.Fun
{
public static class SetFormToModel<T>
{
/// <summary>
/// Assign the form to the object
/// </summary>
/// <param name="t"> Entity objects </param>
/// <param name="form"> Form a collection </param>
public static void GetValue(T t, NameValueCollection form)
{
Type type = t.GetType();
PropertyInfo[] pi = type.GetProperties();
foreach (PropertyInfo p in pi)
{
if (form[p.Name] != null)
{
p.SetValue(t, Convert.ChangeType(form[p.Name], p.PropertyType), null);
}
}
}
/// <summary>
/// Assign objects to the form
/// </summary>
/// <param name="t"> Entity objects </param>
/// <param name="c"> The page object </param>
public static void SetValue(T t,Page page)
{
Type type = t.GetType();
PropertyInfo[] pi = type.GetProperties();
foreach (PropertyInfo p in pi)
{
System.Web.UI.HtmlControls.HtmlInputText text = page.FindControl(p.Name) as System.Web.UI.HtmlControls.HtmlInputText;
if (text != null)
{
text.Value = p.GetValue(t, null).ToString();
}
}
}
}
}
// call
MHouseReco mh = new DHouseReco().GetModel(id);
Com.Fun.SetFormToModel<MHouseReco>.SetValue(mh,this.Page);
MHouseReco mh = new MHouseReco();
Com.Fun.SetFormToModel<MHouseReco>.GetValue(mh, this.Request.Form);