模型::::
public class Model1
{
public string Name { get; set; }
public string ProductName { get; set; }
}
视图模型::::
public class ViewModel1
{
public List<Model1> model1;
}
controller :::::::::
var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
var nmodel = new Model1();
nmodel.Name = gf.Name;
nmodel.ProductName = doSomething(gf.ProductName);
// **Here I'm stuck====how do I add nmodel to newViewModel**
//**newViewModel.Add===does not work**
}
return View(newViewModel);
答案 0 :(得分:1)
根据您发布的代码进行快速猜测,您从未实例化过该集合。
public class ViewModel1
{
List<Model1> model1;
public ViewModel1()
{
model1=new List<Model1>();
}
}
......
newViewModel.model1.Add(nmodel);
答案 1 :(得分:1)
按如下方式更改ViewModel 视图模型::::
public class ViewModel1
{
public List<Model1> model1 = new List<Model1>();
}
按如下方式更改您的控制器:
var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
var nmodel = new Model1();
nmodel.Name = gf.Name;
nmodel.ProductName = doSomething(gf.ProductName);
newViewModel.model1.Add(nmodel);
}
return View(newViewModel);