添加控制器后,模型视图模型字典值为null

时间:2019-02-20 18:44:53

标签: c# dictionary mvvm asp.net-mvc-5

我为有字典的人提供了一个模型来保存性别值(这些值添加在控制器中)。我已经创建了一个带有person类和其他属性的viewmodel。在控制器中,我尝试通过viewmodel实例将值添加到人员类的字典中。它不会引发错误,但是字典值始终为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);
    }

1 个答案:

答案 0 :(得分:0)

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

<nav class="navbar navbar-light bg-black">
  <a class="nav-link" style="color:white" href="https://www.youtube.com/channel/UC_OvfkWfYRvdkazcOoeJd8Q"><img src="img/yt-logo-dark.png" alt="YouTube" height="25px"></a>
  <ul class="nav justify-content-center">
    <li class="nav-item dropdown">
      <a class="nav-link" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" style="color:white"><h2>KJK Music</h2></a>
      <div class="dropdown-menu">
        <a class="dropdown-item disabled" href="about-me">O mně</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item disabled" href="about-site">O stránce</a>
      </div>
     </li>
    </ul>
    <a class="navbar-link" style="color: white" href="https://open.spotify.com/artist/7vlBedEBJhQlJCl1tpknhi"><img src="img/SpotifyIcon.png" alt="Spotify" height="50px" style="margin:12.5px"></a>
</nav>

因为dictViewModel.dictInViewModel.dpdnDict.Add("M", "Male"); 返回dictViewModel.dictInViewModelnew dictionary()dictViewModel.dictInViewModel.dpdnDict,因为null在代码中未设置任何位置。如果您想使此代码生效,请更改您的类

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>()
        };
    }
}
相关问题