Tuesday, June 23, 2015

MVC Web API – Customizing root element name in resultant XML

Problem:

Whenever
we try to return list of an object from API we get an xml response where root
element is ArrayOfYourObjectName that we like to be some plural
form of our object name e.g. if our object name is Student then generated xml’s
root element’s name should beStudents instead of ArrayOfStudent.

Emulating the problem:

We will first create a
table for purpose of illustration as follows

CREATETABLE [dbo].[MyTable](

[Id]INTIDENTITY (1, 1)NOTNULL,

[Name]VARCHAR
(100)NOTNULL,

[Email]VARCHAR
(100)NOTNULL,

[Gender] CHAR (1)NULL,

[Phone]VARCHAR
(20)NULL,

PRIMARYKEYCLUSTERED ([Id] ASC)

);

Add some dummy entries in table.

Now into our MVC web API project add a new class file and
create a class as follows

public class Employee

{

private string _gender;

[Display(Name = "Employee Id")]

public int Id{get;set;}

[Display(Name = "Name")]

[Required]

[StringLength(100)]

public string Name{get;set;}

[Display(Name = "Email")]

[Required]

[StringLength(100)]

public string Email{get;set;}

[StringLength(20)]

public string Phone{get;set;}

public string Gender{

get

{

return _gender;

}

set

{

switch (value)

{

case "M":

_gender = "Male";

break;

case "F":

_gender = "Female";

break;

default:

_gender = "Not
Disclosed";

break;

}

}

}

}

public
class Employees : List<Employee>

{

}

Now add Entity model with name say MyDatabaseEntities

go to Value Controller which usually created by default
and edit get method to resemble below