在控制器中添加模型viewmodel字典值null

问题描述 投票:0回答:1

我有一个人的模型,其中包含用于保存Gender值的字典(值将添加到控制器中)。我创建了一个包含person类和其他属性的viewmodel。在控制器中,我尝试通过viewmodel实例将值添加到person类中的字典中。它不会抛出错误,但字典值始终为null。如果我不使用viewmodel并直接使用模型,代码可以工作。重要!!!! (我必须通过控制器向字典添加值)感谢您的帮助。请在下面编码。在模型中:

public class dictionary
{
    [Display(Name ="Dictionary Dropdownlist")]
    public Dictionary<string,string> dpdnDict { get; set; }
}

在ViewModel中:

public class dictionaryviewmodel
{
    public dictionary dictInViewModel {
        get { return new dictionary(); }
        set { }
    }
}

在控制器中:

    public ActionResult Index(dictionaryviewmodel dictViewModel)
    {
        dictViewModel.dictInViewModel.dpdnDict.Add("M", "Male");
        dictViewModel.dictInViewModel.dpdnDict.Add("F", "Female");
        return View(dictViewModel);
    }
c# dictionary mvvm asp.net-mvc-5
1个回答
0
投票

首先,这段代码确实在这一行上引发了异常

dictViewModel.dictInViewModel.dpdnDict.Add("M", "Male");

因为dictViewModel.dictInViewModel返回new dictionary()dictViewModel.dictInViewModel.dpdnDictnull,因为dpdnDict没有设置在代码中的任何位置。如果你想让这段代码改变你的课程

public class dictionaryviewmodel
{
    public class dictionaryviewmodel
    {
        //this getter will create dictionary instance only once
        //and will always return the same instance with previously added values
        //also it instantiates dpdnDict object
        public dictionary dictInViewModel { get; } = new dictionary()
        {
            dpdnDict = new Dictionary<string, string>()
        };
    }
}

而且我不认为您在请求时将任何数据传递给控制器​​,因此我也会更新控制器

public ActionResult Index()
{
    dictionaryviewmodel dictViewModel = new dictionaryviewmodel();
    dictViewModel.dictInViewModel.dpdnDict.Add("M", "Male");
    dictViewModel.dictInViewModel.dpdnDict.Add("F", "Female");
    return View(dictViewModel);
}
© www.soinside.com 2019 - 2024. All rights reserved.