如何在MVC 5中将一个或多个控制器链接到一个视图

本文关键字:一个 控制器 链接 视图 MVC | 更新日期: 2023-09-27 18:00:14

我正在尝试将多个表中的数据显示到一个视图中,该视图允许用户根据需要添加、更改或删除数据。到目前为止,我甚至还无法获得一个单独的视图来使用一个控制器,更不用说使用一个视图的多个控制器了。我使用的是MVC 5,VS 2013(C#),数据库托管在另一台计算机上。

这是家庭控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vivace.Models;
namespace Vivace.Controllers
{
    public class HomeController : Controller
    {
        public VivaceContext db = new VivaceContext();
        List<Distributor> list = new List<Distributor>();
        public ActionResult Index()
        {
         //   var ist = db.Distributors.FirstOrDefault(x => x.Address == "").Orders.ToList();
         //   var i = db.Distributors.Where(x => x.Address == "").ToList();
            return View();
        }
        public ActionResult About()
        {
            //ViewBag.Message = "Your application description page.";z
            return View();
        }
        public ActionResult Contact()
        {
            //ViewBag.Message = "Your contact page.";
            return View();
        }
        public ActionResult Ordering()
        {
            //ViewBag.Message = "Place your orders."
            return View();
        }
        public ActionResult Inventory(string Categories)
        {
            //ViewBag.Message = "View items currently in stock.";
            var categoriesModel = new Category
            {
                CatName = Categories,
                Items = this.db.Items.ToList()
            };
            return this.View(categoriesModel);
        }
        public ActionResult Item()
        {
            return View();
        }

    }
}

这是项目控制器(项目是我想显示数据的一个表的名称):

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 Vivace.Models;
namespace Vivace.Controllers
{
    public class ItemController : Controller
    {
        private VivaceContext db = new VivaceContext();
        // GET: /Item/
        public ActionResult Index()
        {
            var items = db.Items.Include(i => i.Category1).Include(i => i.Department1).Include(i => i.Distributor1);
            return View(items.ToList());
        }
        // GET: /Item/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Item item = db.Items.Find(id);
            if (item == null)
            {
                return HttpNotFound();
            }
            return View(item);
        }
        // GET: /Item/Create
        public ActionResult Create()
        {
            ViewBag.Category = new SelectList(db.Categories, "CatNumber", "CatName");
            ViewBag.Department = new SelectList(db.Departments, "DeptNum", "DeptName");
            ViewBag.Distributor = new SelectList(db.Distributors, "DistributorNumber", "DistributorName");
            return View();
        }
        // POST: /Item/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ItemNumber,UPC,ItemName,Category,Department,Price,Cost,MarkUp,OnHand,InWherehouse,OnOrder,OnFeature,ShelfCap,Distributor")] Item item)
        {
            if (ModelState.IsValid)
            {
                db.Items.Add(item);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Category = new SelectList(db.Categories, "CatNumber", "CatName", item.Category);
            ViewBag.Department = new SelectList(db.Departments, "DeptNum", "DeptName", item.Department);
            ViewBag.Distributor = new SelectList(db.Distributors, "DistributorNumber", "DistributorName", item.Distributor);
            return View(item);
        }
        // GET: /Item/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Item item = db.Items.Find(id);
            if (item == null)
            {
                return HttpNotFound();
            }
            ViewBag.Category = new SelectList(db.Categories, "CatNumber", "CatName", item.Category);
            ViewBag.Department = new SelectList(db.Departments, "DeptNum", "DeptName", item.Department);
            ViewBag.Distributor = new SelectList(db.Distributors, "DistributorNumber", "DistributorName", item.Distributor);
            return View(item);
        }
        // POST: /Item/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ItemNumber,UPC,ItemName,Category,Department,Price,Cost,MarkUp,OnHand,InWherehouse,OnOrder,OnFeature,ShelfCap,Distributor")] Item item)
        {
            if (ModelState.IsValid)
            {
                db.Entry(item).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Category = new SelectList(db.Categories, "CatNumber", "CatName", item.Category);
            ViewBag.Department = new SelectList(db.Departments, "DeptNum", "DeptName", item.Department);
            ViewBag.Distributor = new SelectList(db.Distributors, "DistributorNumber", "DistributorName", item.Distributor);
            return View(item);
        }
        // GET: /Item/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Item item = db.Items.Find(id);
            if (item == null)
            {
                return HttpNotFound();
            }
            return View(item);
        }
        // POST: /Item/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Item item = db.Items.Find(id);
            db.Items.Remove(item);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

这是我想要显示数据的视图(文本框用于提交新数据,即订单,或搜索以前的订单):

@{
    ViewBag.Title = "Ordering";<input id="Text1" type="text" />
}
<h2>Ordering</h2>
<fieldset>
    <legend>Order Information</legend>
    <form>
        <p><label for="distributor">Distributor:</label>
           <input type="text" name="distributor" value="@Request.Form["distributor"]" /></p>
        <p><label for="product">Product:</label>
           <input type="text" name="product" value="@Request.Form["product"]"/></p>
        <p><label for="quantity">Quantity:</label>
           <input type="number" name="quantity"  value="@Request.Form["quantity"]"/></p>
        <p><label for="date">Date:</label>
           <input type="date" name="date" value="@Request.Form["date"]"/></p>
        <input type="submit" value="Place Order">
    </form>
    <legend>Order History</legend>
    <label>Search by:</label>
    <form>
        <p>
            <label for="distributorHist">Distributor:</label>
            <input type="text" name="distributorHist" value="@Request.Form["distributorHist"]" /></p>
        <p>
            <label for="productHist">Product:</label>
            <input type="text" name="productHist" value="@Request.Form["productHist"]" /></p>
        <p>
            <label for="dateHist">Date:</label>
            <input type="date" name="dateHist" value="@Request.Form["dateHist"]" /></p>
        <input type="submit" value="View History">
    </form>
</fieldset>

有什么东西我遗漏了吗?

编辑:我想我已经学会了如何实现局部视图,但现在我遇到了一个新错误:

Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 
Compiler Error Message: CS0103: The name 'item' does not exist in the current context
Source Error:

Line 36: 
Line 37:     <td>
Line 38:         @Html.DisplayFor(modelItem => item.UPC)
Line 39:     </td>
Line 40:     <td>
Source File: c:'Users'Dragonfett'Documents'School'Spring 2014'CMPS 285'Group_6-CMPS_285'Vivace'Vivace'Views'Home'Ordering.cshtml    Line: 38 

Show Detailed Compiler Output:
Show Complete Compilation Source:

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009

我将这段代码从名为Index的Item View移到了Ordering View:

<td>
        @Html.DisplayFor(modelItem => item.UPC)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ItemName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Cost)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.MarkUp)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.OnHand)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InWherehouse)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.OnOrder)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.OnFeature)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ShelfCap)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Category1.CatName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Department1.DeptName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Distributor1.DistributorName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.ItemNumber }) |
        @Html.ActionLink("Details", "Details", new { id = item.ItemNumber }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.ItemNumber })
    </td>

我迷路了。

如何在MVC 5中将一个或多个控制器链接到一个视图

将公共视图设为部分视图。

每个控制器的每个视图都有一个单独的cshtml,但只让它们加载部分视图。

您可以使用ViewBag存储一个表的数据并将其传递给View,同时将其他表数据作为要查看的模型传递。但最好的方法是为视图创建一个ViewModel类,然后将该ViewModel类映射到Model(域)类。使用automapper将ViewModel映射到Model类。

http://www.codeproject.com/Articles/687061/Using-Multiple-Models-in-a-View-in-ASP-NET-MVC-M