Reputation: 973
I would like to add an mock entity of my model to an existing json as a new entity. In this code example: how can I add model2 to js?
public JsonResult Get()
{
Employee model1 = new Employee();
Employee model2 = new Employee();
model1.id = 1;
model1.name = "Fritz";
model2.id = 2;
model2.name = "Emil";
JsonResult js = new JsonResult(model1);
return js;
}
Upvotes: 0
Views: 41
Reputation: 1774
You can add model2 into the result as follows.
JsonResult js = new JsonResult(new { Model1 = model1, Model2 = model2 });
Upvotes: 0
Reputation: 218732
You can create a list/array of Employee
objects and add your 2 objects (model1 and model2) to that list and send the list.
public JsonResult Get()
{
var model1 = new Employee();
model1.id = 1;
model1.name = "Fritz";
var model2 = new Employee();
model2.id = 2;
model2.name = "Emil";
var list= new List<Employee> { vmodel1, model2 };
return Json(list);
}
If this action method is HttpGet type, you should explicitly specify that when calling the Json
method by using the JsonRequestBehavior
enum.
return Json(list,JsonRequestBehavior.AllowGet);
This will return a response like below. An array of two items.
[{"id":1,"name":"Fritz"},{"id":2,"name":"Emil"}]
I also suggest you to use PascalCasing for the class property names. Id
and Name
instead of id
and Name
Upvotes: 1