1

我是 asp.net mvc4 的新手,并在其中创建了一个项目。我被困在路上了。

首先让我描述一下我的项目。我正在创建一个产品表,每个产品都有一些属性。我创建了一个ProductAttribute模型和一个AttributeValue模型来添加属性及其值。然后我创建了一个ProductAttributeValue模型来将属性及其值分配给产品。

现在我的问题是我想使用相同的视图来添加属性及其值。以下是我的模型:

[Table("ProductAttribute")]
public class ProductAttribute
{
    [Key]
    [MaxLength(20)]
    public string AttributeId { get; set; }

    [Required]
    [Display(Name = "Attribute Name")]
    [MaxLength(100)]
    public string AttributeName { get; set; }

    [Required]
    [Display(Name = "Datatype")]
    [MaxLength(50)]
    public string AttributeDatatype { get; set; }

    [Required]
    [Display(Name = "Is Active")]
    public bool IsActive { get; set; }

    [Required]
    [Display(Name = "Attribute Type")]
    [MaxLength(30)]
    public string AttributeType { get; set; }
}

[Table("AttributeValue")]
public class AttributeValue
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(20)]        
    public string AttributeId { get; set; }

    [Required]
    [MaxLength(100)]
    public string AttributeName { get; set; }

    [Required]
    [MaxLength(200)]
    public string AttributeVal { get; set; }

    public virtual ProductAttribute ProductAttribute { get; set; }
}

如何使用一个视图和控制器将值插入不同的表?如果有另一种方法可以做到这一点,那么请帮助我。

谢谢

4

1 回答 1

0

我想我明白你在说什么。首先,您将要构建一个视图模型。就像是

public Class Tables
{
    public List<ProductAttribute> Products { get; set; }
    public List<AttributeValue> Values { get; set; }
}

从您的控制器设置这些列表并将它们传递给视图。在视图上,您​​将定义模型,如

@model Tables

然后在视图中以您喜欢的方式构建您的表格。我过去使用过 Html.WebGrid,但最近只使用了 foreach 循环

<table>
foreach(var temp in Model.Products)
{
     <tr>
         <td>
               temp.Name, etc
         </td>
     </tr>
}
</table>

至于添加和创建,我从来都不喜欢直接在表格中创建或添加,通常我在表格中显示的并不是我想要的所有信息,所以我使用上下文菜单或编辑按钮行,然后是上下文菜单中的添加按钮,或者就在表格之外,它将重定向到编辑/添加页面,然后返回。然后,您可以使用回发、jquery 刷新表格,刷新局部视图,无论哪种方式最适合您的情况。希望这会有所帮助 :) 哦,这是一个链接,供人们讨论如何最好地编辑表格 如何编辑表格数据(ASP MVC)

更新:通过模型传递给视图并在页面上使用 for(html.textboxfor、textareafor 等)的任何信息都将传递回控制器。如果这些字段被更改,那么更改的值将被传回。

public ActionResult Index(){
    (build your table class)
    return View(Tables);
}

[HttpPost]
public ActionResult Index(Tables tbl){
     (pass values return from the view to your query for saving to the database)
{
于 2013-09-13T20:04:48.473 回答