ASP MVC4 - 山口列表通过视图模型视图 [英] ASP MVC4 - Pass List to view via view model

查看:143
本文介绍了ASP MVC4 - 山口列表通过视图模型视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型的人(出生与其他领域之间的日)
我想传递的所有人员的名单,与每个人的年龄计算一起,到视图

I have a model Person (with among other fields the day of Birth) and I want to pass a list of all persons, together with the calculated age of each person, to the view

为此:


  1. 视图模式

  1. The view model

public class vm_PersonList
{
    public Person Person { get; set; } 
    public int age { get; set; }
}


  • 控制器动作:

  • The controller action:

    public ActionResult PersonList()
    {
        ViewBag.Message = "My List";
    
        var list = new List<vm_PersonList>();
        var list_p = new vm_PersonList();
    
    
        foreach (var p in db.Person)
        {
            list_p.Person = p;
            //the age will be calculated based on p.birthDay, not relevant for the    
            //current question
            list_p.age = 23;
    
            list.Add(list_p);
        }
        return View(list);
    }
    


  • 视图

  • The view

    @model List<programname.Viewmodels.vm_PersonList>
    
    @foreach (var p in Model)
    {
        <tr>
            <td>
                @p.Person.FullName
            </td>
            <td>
                @p.age
            </td>  
        </tr>
    }
    


  • person表例如包含6项。
    当调试应用程序我看到:

    The Person table contains for example 6 entries. When debugging the application I see:

    在控制器动作结束名单中包含了正确的6种不同的人物条目

    At the end of the controller action "list" contains correctly the 6 different Person entries

    在该视图中,模式包含6个表项,但6次最后的数据库条目。
    有没有人有一个建议来解决这个问题呢?

    In the view, the "Model" contains 6 entries, but 6 times the last "database entry". Does anyone have a suggestion to solve this issue?

    推荐答案

    正在一遍又一遍地使用同样的 list_p 再比如在循环中。所以,你在不断更新其个人财产。而且,由于是要修改内存中的相同的参考引用类型。在循环的最后一次迭代,你显然与替代人的最后一个实例这就解释了为什么你看到在视图中同一人该引用。

    You are using the same list_p instance over and over again inside the loop. So you are constantly updating its Person property. And since Person is a reference type you are modifying the same reference in memory. At the last iteration of the loop you are obviously replacing this reference with the last instance of Person which explains why you are seeing the same person in the view.

    试试这个样子,显得轻松不少:

    Try like this, seems lot easier:

    public ActionResult PersonList()
    {
        ViewBag.Message = "My List";
        var model = db.Person.Select(p => new vm_PersonList
        {
            Person = p,
            age = 23
        }).ToList();
        return View(model);
    }
    

    这篇关于ASP MVC4 - 山口列表通过视图模型视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆