问题描述
我想将模型的模拟实体作为新实体添加到现有json中.在此代码示例中:如何将 model2 添加到 js ?
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;
}
推荐答案
您可以创建Employee
对象的列表/数组,并将2个对象(model1和model2)添加到该列表中并发送该列表.
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);
}
如果此操作方法是HttpGet类型,则在使用JsonRequestBehavior
枚举调用Json
方法时,应明确指定该方法.
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"}]
我还建议您将PascalCasing用于类属性名称. Id
和Name
而不是id
和Name
I also suggest you to use PascalCasing for the class property names. Id
and Name
instead of id
and Name
这篇关于在MVC控制器中将实体添加到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!