【发布时间】:2010-03-07 05:08:34
【问题描述】:
表产品
产品编号
产品名称
表 ProductSupplier
产品供应商 ID
产品编号
供应商编号
表供应商
供应商 ID
供应商名称
我的数据库中有上述 3 个表,ProductSupplier 是查找表。每个产品可以有多个供应商。我正在使用实体框架。
使用 Web 表单在网页上显示产品并将转发器与供应商信息绑定相当容易。
此外,使用 Web 表单很容易添加新产品和供应商,链接似乎很容易。
如何在 MVC 中实现这种功能?
在下面的创建视图中,我也希望能够添加供应商。
有没有更好的方法我可能会在这里遗漏?
这就是我使用 Web 表单的方式。
在下面的代码之外,我完全迷失了。我可以在列表中显示数据,也可以显示每个产品的供应商,但我如何添加和编辑。我应该把它分成不同的观点吗?使用 Web 表单,我可以在一个页面中完成所有操作。
namespace MyProject.Mvc.Models
{
[MetadataType(typeof(ProductMetaData))]
public partial class Product
{
public Product()
{
// Initialize Product
this.CreateDate = System.DateTime.Now;
}
}
public class ProductMetaData
{
[Required(ErrorMessage = "Product name is required")]
[StringLength(50, ErrorMessage = "Product name must be under 50 characters")]
public object ProductName { get; set; }
[Required(ErrorMessage = "Description is required")]
public object Description { get; set; }
}
public class ProductFormViewModel
{
public Product Product { get; private set; }
public IEnumerable<ProductSupplier> ProductSupplier { get; private set; }
public ProductFormViewModel()
{
Product = new Product();
}
public ProductFormViewModel(Product product)
{
Product = product;
ProductSupplier = product.ProductSupplier;
}
}
}
ProductRepository
public Product GetProduct(int id)
{
var p = db.Product.FirstOrDefault(por => por.ProductId == id);
p.ProductSupplier.Attach(p.ProductSupplier.CreateSourceQuery().Include("Product").ToList());
return p;
}
产品创建视图
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyProject.Mvc.Models.ProductFormViewModel>" %>
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.ProductId) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Product.ProductId) %>
<%= Html.ValidationMessageFor(model => model.Product.ProductId) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.ProductName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Product.ProductName) %>
<%= Html.ValidationMessageFor(model => model.Product.ProductName) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.Description) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Product.Description) %>
<%= Html.ValidationMessageFor(model => model.Product.Description) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
【问题讨论】:
-
aspx 视图或 ascx 部分应该是什么样子?
标签: asp.net entity-framework asp.net-mvc-2