Convert 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
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.
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 |
Read the below complex model structure we used in this project for the demo
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; }
}
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();
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
Sanal Menon Kalipurayath (@sanalmenon)
Web: sanal.menon.me
LinkedIn: https://in.linkedin.com/menon
Twitter: https://www.twitter.com/sanalmenon