从控制器传递几个数据到视图

时间:2015-06-27 02:50:12

标签: c# asp.net-mvc

似乎无法找到答案,我是.net的菜鸟。我正试图从控制器传递几个数据到视图。

这是我的控制器

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ProjectWizNet.Models;

namespace ProjectWizNet.Controllers
{
    public class ClientController : Controller
    {
        private MyDbContext db = new MyDbContext();

    }

    // GET: Client/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            return View("_RecordNotFound");
        }

        Client client = db.Clients.Find(id);
        var projects = from p in db.Projects
            where p.ClientId == id
            select p;

        if (client == null)
        {
            //return HttpNotFound();
            return View("_RecordNotFound");
        }

        ViewBag.Title = "Edit";

        return View(client);
    }
}

所以我有客户端查询数据库以获取客户端记录。我也有项目查询外键是projects.ClientId的数据库。我迷路的地方是

return View(client)

我来自laravel php,我将如何使用数据数组。像

这样的东西
$data["clients"] = my query to get client;
$data["projects"] = my query to get project;

return view($data);

在.net mvc中是一种类似的方法吗?还是以不同的方式?创建模型视图?

2 个答案:

答案 0 :(得分:3)

控制器不应直接将域模型(客户端和项目)传递给View。相反,您需要将它们转换为View Models。

模型

public class ClientViewModel
{
   // Properties
}

public class ProjectViewModel
{
   // Properties
}

public class EditViewModel
{
    public ClientViewModel Client { get; set; }
    public IList<ProjectViewModel> Projects { get; set; }
}

控制器

如果您的项目很大,则需要使用AutoMapper

var clientViewModel = db.Clients.Where(x => x.Id == id)
    .Select(x => new ClientViewModel
    {
        // Map Client domain model to Client view model
    })
    .FirstOrDefault();

var projectViewModels = from p in db.Projects
    where p.ClientId == id
    select new ProjectViewModel
    {
        // Map Project domain model to Project view model
    };

var editViewModel = new EditViewModel
    {
        Client = clientViewModel,
        Projects = projectViewModels
    };

return View(editViewModel);

视图

@model YourProjectNamespace.Models.EditViewModel

@foreach (var project in Model.Projects)
{
    // Print project
}

答案 1 :(得分:2)

您可以使用ViewData。如果要将数据带到视图并显示它,可以在控制器中使用以下内容。

ViewData["projects"] = project.ToList();

在视图中你可以做这样的事情

<ul>
<% foreach(var item in (ViewData["projects"] as List<Project>)){%>
   <li>
       <%=item.ClientName%>
   </li>
<% } %>
</ul>

我的偏好是使用ViewModels,因为它更有条理,但这对简单的页面很有用。如果你愿意,我可以给你一个例子。