为控制器中的复杂变量赋值,我得到的对象引用未设置为对象的实例

时间:2015-09-05 16:43:29

标签: c# model-view-controller

public class kingdomAddModel
{
    public string title { get; set; }
    public string details { get; set; }
    //public HttpPostedFileBase fileUpload { get; set; }
    //public string retrieveFile { get; set; }
    public  FileAttr files { get; set; }
}

public class FileAttr
{
    public HttpPostedFileBase fileUpload { get; set; }
    public string retrieveFile { get; set; }
}

var getDailyDevotions = db.DailyDevotions.Select(d => new { title = d.DevotionsTitle, details = d.DevotionsDetails, retriveFileAudio = d.VoiceNotes });
List<kingdomAddModel> listdevotions = new List<kingdomAddModel>();
foreach (var getDevotions in getDailyDevotions)
{
    kingdomlist = new kingdomAddModel();
    kingdomlist.title = getDevotions.title;
    kingdomlist.details = getDevotions.details;
    fileattr = new FileAttr();
    fileattr.retrieveFile = getDevotions.retriveFileAudio;
    kingdomlist.files.retrieveFile = fileattr.retrieveFile; //erros appears here!
}

线条kingdomlist.files.retrieveFile抛出异常,尝试谷歌搜索,但我没有得到类似的问题。我只是想分配价值并继续我的观点。

1 个答案:

答案 0 :(得分:1)

不要直接访问FileAttr的属性,只能使用files实例kingdomAddModel。不要混淆他们

替换

foreach (var getDevotions in getDailyDevotions)
{
    kingdomlist = new kingdomAddModel();
    kingdomlist.title = getDevotions.title;
    kingdomlist.details = getDevotions.details;
    fileattr = new FileAttr();
    fileattr.retrieveFile = getDevotions.retriveFileAudio;
    kingdomlist.files.retrieveFile = fileattr.retrieveFile; //erros appears here!
}

foreach (var getDevotions in getDailyDevotions)
{
    kingdomlist = new kingdomAddModel
    {
        title = getDevotions.title,
        details = getDevotions.details,
        files = new FileAttr
        {
            retrieveFile = getDevotions.retriveFileAudio,
            //fileUpload = some value here
        }
    };
    listdevotions.Add(kingdomlist);
}

或使用Linq

listdevotions = (from getDevotions in getDailyDevotions
                select new kingdomAddModel                
                {
                    title = getDevotions.title,
                    details = getDevotions.details,
                    files = new FileAttr
                    {
                        retrieveFile = getDevotions.retriveFileAudio,
                        //fileUpload = some value here
                    }
                }).ToList();