加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-2 – 如何从同一视图更新一对多关系实体?

发布时间:2020-12-16 07:43:24 所属栏目:asp.Net 来源:网络整理
导读:表产品 产品编号 产品名称 表供应商 供应商ID 产品编号 供应商名称 当我创建一个新产品时,我希望有一个文本框也可以在同一个视图中输入供应商.这是一个好习惯吗?由于产品可以有许多供应商,我希望能够从同一视图添加更多供应商记录.我怎么做? 我想弄清楚我
表产品
产品编号
产品名称

表供应商
供应商ID
产品编号
供应商名称

当我创建一个新产品时,我希望有一个文本框也可以在同一个视图中输入供应商.这是一个好习惯吗?由于产品可以有许多供应商,我希望能够从同一视图添加更多供应商记录.我怎么做?

我想弄清楚我在aspx页面中放了什么?

如果我输入类似<%= Html.TextBoxFor(model => model.Supplier)%>我看到一个带有System.Data.Objects.DataClasses.EntityCollection`1 [MyProject.Mvc.Models.Supplier]的文本框.

<%@ 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>

<% } %>

ProductViewModel

public class ProductFormViewModel
{
    public Product Product{ get; private set; }
    public IEnumerable<Supplier> Supplier { get; private set; }

    public ProductFormViewModel()
    {
        Product = new Product();
    }

    public ProductFormViewModel(Product product)
    {
        Product = product;
        Supplier = product.Supplier;
    }
}

解决方法

我想你会发现 Steven Sanderson’s blogpost about editing variable length lists in ASP.NET MVC 2非常有用.他还有另一个 blogpost about validating such a list.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读