我的控制器代码有问题

时间:2014-05-07 15:07:22

标签: asp.net-mvc asp.net-mvc-4

我的控制器

public ActionResult Index()
{
    TechnicianFacade _oTechFacade = new TechnicianFacade();
    Maintenance_.Models.IndexModel _oTechModel = new Maintenance_.Models.IndexModel();
    IList<Maintenance_.Models.IndexModel> _otechList = new List<Maintenance_.Models.IndexModel>();

    var tech = _oTechFacade.getTechnicians("", _oAppSetting.ConnectionString).ToArray();
    foreach (var test in tech)
    {
       string fName = test.GetType().GetProperty("FIRSTNAME").GetValue(test, null).ToString();
        _oTechModel.firstName = fName;
        _otechList.Add(_oTechModel);         <===
    }
    _oTechModel.fNameList = _otechList;
    return View("Index", _oTechModel);                                 
}

在我的控制器:index中,可以从我的数据库中获取所有数据对象。但是如果我的数据库中有多个数据对象,则:_otechList.Add(_otechModel)将用新添加的数据覆盖第一个条目,例如,假设我们有2个对象数据:( foreach的FIRST循环)< em> _otechList.Add(_oTechModel)的数据为&#34; FIRSTNAME&#34; =&#34; GEM&#34; 其中count = 0,(foreach的第二个循环) _otechList.Add(_oTechModel)的数据为&#34; FIRSTNAME&# 34; =&#34; DIAMOND&#34; 其中count = 1,这次count [0]的值变为&#34; FIRSTNAME&#34; =&#34; DIAMOND&#34; 。我的代码中是否缺少某些内容,或者其中有什么问题?

1 个答案:

答案 0 :(得分:0)

它将被替换,因为相同的对象值被更改,您需要在foreach循环内实例化对象。

Maintenance_.Models.IndexModel _oTechModel = new Maintenance_.Models.IndexModel();
像这样:

foreach (var test in tech)
    {
       string fName = test.GetType().GetProperty("FIRSTNAME").GetValue(test, null).ToString();
        Maintenance_.Models.IndexModel _oTechModel = new Maintenance_.Models.IndexModel();
        _oTechModel.firstName = fName;
        _otechList.Add(_oTechModel);        
    }

您的object是全局的,因此每次在列表中添加object时,都会在 foreach 循环中对其进行实例化,以便每次添加新的object时在列表中。