Search code examples
c#asp.netquery-stringhttpcontext

Simplify getting the data from the form


I filled out the form, and received data on the server like this:

model.Firstname = HttpContext.Current.Request.QueryString["Firstname"];
model.Lastname = HttpContext.Current.Request.QueryString["Lastname"];
model.Middlename = HttpContext.Current.Request.QueryString["Middlename"];
model.Avatar = HttpContext.Current.Request.QueryString["Avatar"];
model.Birthday = HttpContext.Current.Request.QueryString["Birthday"];

Model:

public int CustomerID { get; set; }
public int StatusID { get; set; }
public string Firstname { get; set; }
public string Lastname{ get; set; }
public string Middlename { get; set; }
public string Birthday { get; set; }

Is there any way to make it easier and combine this lines?


Solution

  • You can write an extension method and use reflection to set your properties, like this:

    public static void SetProperties<T>(this T source, HttpContext context)
    {
         var properties = typeof(T)
                 .GetProperties(BindingFlags.Instance | BindingFlags.Public);
    
         var  values = context.Request.QueryString;
    
         foreach (var prop in properties)
         {
             if (values.AllKeys.Contains(prop.Name))
             {
                 prop.SetValue(source,values[prop.Name]);
             }
         }
    }
    

    Usage:

    mode.SetProperties(HttpContext.Current);
    

    This assumes that your keys in the query string are exactly matches with your property names of the model.