How to map 2 diffrent List in asp.net MVC

2019-07-12 13:57发布

问题:

I was trying to send a list from Controller to 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'). So how am I supposed to map both list?

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>

回答1:

You almost had it:

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

            return View(newList);
        }


回答2:

Just make new List of NewListViewModel class then fill it with oldList data

public ActionResult MyData()
{
    var oldList = db.oldList.Select(x=>x.Name).ToList();
    var newList=new list<NewListViewModel>();
      foreach(var item in oldList)
      {
       newList.Add(new NewListViewModel{Name=item.Name});
      }
    return View(newList);
}


回答3:

You can do what @arash.zh has suggested. Or you can just use

@model dynamic

instead of

@model IEnumerable<MyApp.ViewModels.NewListViewModel>