Search code examples
c#asp.netentity-frameworkormmapping

How to map 2 different Lists in asp.net MVC


I was trying to send a list from a Controller to a View. I thought it would bind, but it's a different type so it won't. (error: Argument type 'System.Collections.Generic.List' is not assignable to model type 'System.Collections.Generic.IEnumerable<MyApp.ViewModels.NewListViewModel>'). So how am I supposed to map both lists?

Controller

 public ActionResult MyData()
    {
        var oldList = db.oldList.Select(x=>x.Name).ToList();
    
// probably here i should add var newList and in some way map with oldList then return to view

        return View(oldList);
    }

New list ViewModel

 public class NewListViewModel
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }

My View (MyData)

@model IEnumerable<MyApp.ViewModels.NewListViewModel>
           
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Count)
        </th>
    </tr>

    @foreach (var item in Model)
    {
        using (Html.BeginForm())
        {
            <tr>
                <td>
                    @Html.TextBoxFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.TextBoxFor(modelItem => item.Count)
                </td>
            </tr>
        }
    }
</table>

Solution

  • You almost had it:

        public ActionResult MyData()
            {
                List<NewListViewModel> newList = 
                     db.oldList.Select(x=>new NewListViewModel { Name = x.Name}).ToList();
    
                return View(newList);
            }