通过ViewBag传递模型对象

时间:2015-10-02 12:15:40

标签: asp.net-mvc-3 viewbag

我想知道是否可以通过ViewBag传递模型对象。我尝试了以下代码,但在我的视图中,它只是显示模型的路径。

控制器:

public ActionResult Tempo()
{
    DateTime date1 = new DateTime(1990, 1, 1);
    Employee emp = new Employee(3, "fara", "hass", date1, 56.6m, 0);
    ViewBag.EmployeeId = emp.EmployeeID;
    ViewBag.Fname = emp.Fname;
    ViewBag.Employee = emp;
}

查看:

@{
    ViewBag.Title = "Tempo";
}

@model LayoutProject.Models.Employee

<h2>Tempo</h2>
<div>
    <h4>ViewBag</h4>
    <br />
    EmployeeID: @ViewBag.EmployeeId
    <br />
    Fname: @ViewBag.Fname
    <br />
    Employee : @ViewBag.Employee
</div>

正确显示Fname和EmployeeId,但不显示Employee本身。我在这里遗漏了什么,或者根本无法通过ViewBag传递模型吗?

1 个答案:

答案 0 :(得分:2)

最好创建视图模型以传递给视图:

public class TempoViewModel
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }

    public string LastName { private get; set; }
    public DateTime EmployeeStartDate { private get; set; }
    //any other properties here that make up EmployeeInformation

    public string EmployeeInformation
    { 
        get
        {
            //Format your employee information in the way you intend for the view
            return string.Format("Employee: {0}, {1}, {2}", this.FirstName, this.LastName, this.EmployeeStartDate);
        }
    }
}

然后让控制器创建视图模型:

public ViewResult Tempo()
{
    employee = //logic to retrieve employee information

    //map model to viewmodel
    var viewModel = new TempoViewModel()
    {
        EmployeeId = employee.EmployeeID,
        FirstName = employee.Fname,
        LastName = employee.Lname, //or set whatever properties are required to display EmployeeInformation
        EmployeeStartDate = employee.StartDate,
    };

    return View(viewModel);
}

然后在视图中显示视图模型:

@model TempoViewModel

@{
    ViewBag.Title = "Tempo";
}

<h2>Tempo</h2>
<div>
    <h4>Tempo Employee Information</h4>
    <br />
    EmployeeID: @Model.EmployeeId @* Do you really want to display the employee id? *@
    <br />
    Fname: @Model.FirstName
    <br />
    Employee: @Model.EmployeeInformation
</div>

<强>更新

使用当前的实现,在视图中调用@ViewBag.Employee时要尝试实现的是将模型写为字符串表示形式。使用当前实现,要将模型转换为字符串,将调用模型的ToString()方法。由于您(可能)没有覆盖ToString()方法,因此调用继承的对象实现,它会写出完整的命名空间和类名(这就是我所说的当你说路径时的意思)。

要更正当前的解决方案,您可以向Employee类添加ToString()的实现。例如:

public class Employee
{
    public Employee(int employeeId, string firstName, string lastName)
    {
        this.EmployeeId = employeeId;
        this.FName = firstName;
        this.LName = lastName;
        //etc
    }

    public int EmployeeId { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }

    public override string ToString()
    {
        //Implement your required string representation of the object here
        return string.Format("EmployeeId: {0}, FName: {1}, LName: {2}", EmployeeId, FName, LName);
    }
}