Model to Querystring

Convert Model to Querystring

Build status

View the Project on GitHub sanalmenon/ModelToQuerystring

Model to Querystring

Model to Querystring is an extension method, which will help you to generate the Querystring from the model. This is a very useful extension to use when working with Web API or systems with multiple web API calls.

Install-Package Menon.Me.ModelToQuerystring

Query Parameter Attribute

QueryParameter gives you the flexibility to control the querystring parameters that you are generating. Either by changing property name to a different name or you can ignore the entire property while generating querystring parameters.

  1. some cases we have the model property name and expected querystring property name might be different
  2. or, we do not require the property to be added to the querystring

The default value for the IsQuerystring is always true

[QueryParameter(PropertyName = "eId", IsQuerystring = true)]
public int EmployeeId { get; set; }
Property Name Value
PropertyName you can write custom property name
IsQuerystring true/false

Example

Read the below complex model structure we used in this project for the demo

Creating Model Class

public class BasePageModel
{
    [QueryParameter(PropertyName = "pageId", IsQuerystring = true)]
    public int PageId { get; set; } = 1;

    [QueryParameter(PropertyName = "pageSize", IsQuerystring = true)]
    public int PageSize { get; set; } = 10;
}

public class EmployeeModel : BasePageModel
{
    [QueryParameter(PropertyName = "eId", IsQuerystring = true)]
    public int EmployeeId { get; set; }

    [QueryParameter(PropertyName = "joiningDate", IsQuerystring = true)]
    public string JoiningDate { get; set; } = string.Empty;

    public string EmployeeName { get; set; }

    public AddressInfo Address { get; set; }
}

public class AddressInfo
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}

Converting Model to Querystring

This is how you you can call the extension

var model = new EmployeeModel()
{
    EmployeeId = 1,
    EmployeeName = "Some one",
    JoiningDate = DateTime.Now.Date.ToString("dd/MM/yyyy"),
    Address = new AddressInfo()
    {
        Address1 = "506, some building",
        Address2 = "some street, area",
        City = "Dubai",
        State = "Dubai",
        Country = "United Arab Emirates"
    }
};

var result = model.ToQueryString();

Result

eId=1&joiningDate=22-11-2016&EmployeeName=Some one&AddressInfo.Address1=506, some building&AddressInfo.Address2=some street, area&AddressInfo.City=Dubai&AddressInfo.State=Dubai&AddressInfo.Country=United Arab Emirates&pageId=1&pageSize=10

Authors and Contributors

Sanal Menon Kalipurayath (@sanalmenon)
Web: sanal.menon.me
LinkedIn: https://in.linkedin.com/menon
Twitter: https://www.twitter.com/sanalmenon