DropDownListFor and binding my lambda to my ViewModel

After I have worked with Internet search, I am still drawing a space here. I am trying to use ViewModel to pull out and provide a dictionary in a dropdown list inside a strongly typed view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="EveNotebook.ViewModels.CorporationJoinViewModel" %>

...

<%: Html.DropDownListFor(c => c.CorpDictionary.Keys, new SelectList(Model.CorpDictionary, "Value", "Key"))%>

I get an error message:

CS1061: "object" does not contain a definition for "CorpDictionary", and the extension method "CorpDictionary" cannot be found that takes the first argument of type "object"

and the corresponding bit of my ViewModel

   public class CorporationJoinViewModel
    {
        DB _eveNotebook = new eveNotebookDB(); // data context

        public Dictionary<int, string> CorpDictionary
        {
            get
            {
                Dictionary<int, string> corporations = new Dictionary<int, string>();

                int x = 0;
                foreach (Corporation corp in _db.Corporations)
                {
                    corporations.Add(x, corp.name);
                }

                return corporations;
            }
        }

, , linq ViewModel , , . , ? ?


( , ):

  var model = new CorporationJoinViewModel
                {
                    Corps = _eveNotebook.Corporations.Select( c => new SelectListItem
                                     {
                                          Text = c.name,
                                          Value = c.id.ToString()
                                     })
                };

    return View(model);

Inherits="System.Web.Mvc.ViewPage<IEnumerable<EveNotebookLibrary.Models.Corporation>>" %>

...

<%: Html.DropDownListFor(c => c.Corps, new SelectList(Model.Corps))%>

ViewModel

public class CorporationJoinViewModel : ViewPage
{
    public int CorporationId { get; set; }

    public IEnumerable<SelectListItem> Corps { get; set; }
}
+3
1

-, , , . -, ViewPage, , , . -, , CorporateId ( select) IEnumerable<SelectListItem> , SelectList. LINQ .

, - , - ​​ . .

<%@ Page Title="" Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<EveNotebook.ViewModels.CorporationJoinViewModel>"
 %>

<%: Html.DropDownListFor(c => c.CorporationId, Model.CorpDictionary )%>

public class CorporationJoinViewModel
{
    public int CorporationId { get; set; }

    public IEnumerable<SelectListItem> CorpDictionary { get; set; }
}

...
var model = new CorporationJoinViewModel
            {
                CorpDictionary = _eveNotebook.Corporations.Select( c => new SelectListItem
                                 {
                                      Text = c.name,
                                      value = c.id.ToString()
                                 }
            };
+3

Source: https://habr.com/ru/post/1746757/


All Articles