我有一个DTO(或POCO类,不确定正确的术语是什么)类(在模型中)具有以下值:
public class MainDTO
{
public CustomerDTO[] customer { get; set; }
public string itemPurchased { get; set; }
public int staffId { get; set; }
}
public class CustomerDTO
{
public string name { get; set; }
public string[] address { get; set; }
}
我在一个REST webservice调用之后在我的MVC应用程序中调用它,它返回一个带有上述类值的Json。
我想在控制器中对这些值进行硬编码,以便我可以测试视图。但是,我不知道如何硬编码调用另一个类的值。
//Response variable below contains Json result of the web service call
var root = JsonConvert.DeserializeObject<GETModel.MainDTO>(response);
//Hard-coding values to test view
root.customer = ? //How can I hard-code this value?
root.itemPurchased = “Random Item”;
root.staffId = 2299;
return View(root);
如何对“root.customer”变量进行硬编码?它包含一个数组和字符串变量。
答案 0 :(得分:3)
创建该类的新实例(或者更确切地说是该类实例的新数组)并填充它。
root.customer = new CustomerDTO[]
{
new CustomerDTO()
{
name = "",
address = new string[]
{
"value1",
"value2"
}
}
};
由于它是一个有公共制定者的公共课,你可以很容易地做到这一点。
答案 1 :(得分:0)
虽然我不喜欢硬编码,但你可以这样做。
List<CustomerDTO> customers = new List<CustomerDTO>();
var customer1 = new CustomerDTO();
customer1.name = "xyz";
customer1.address = new string[1];
customer1.address[0] = "123, xyz st, city, state";
var customer2 = new CustomerDTO();
customer2.name = "abc";
customer2.address = new string[1];
customer2.address[0] = "123, abc st, city, state";
customers.Add(customer1);
customers.Add(customer2);
//Hard-coding values to test view
root.customer = customers.ToArray();
root.itemPurchased = “Random Item”;
root.staffId = 2299;
return View(root);