在一个步骤中创建项目并为项目添加图像

本文关键字:项目 创建 图像 添加 一个 | 更新日期: 2023-09-27 18:10:40

我正试图通过制作电子商务网站来学习ASP.net。我正在尝试设置创建项目的能力,并通过文件上传将图像分配给正在创建的项目。

我设法让多个文件上传工作,但只到内容/图像文件夹。我想不出该如何将此功能与Items的创建结合起来,这样您就可以在创建项目时为一个项目分配多个图像。

公平地说,我不知道该怎么做,希望你能帮助我。

Item Model Class:数据库中存储每个项目的表。从Images表中引用,关系为1到多。

 public class Item
 {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ItemId { get; set; }
    public int CategoryId { get; set; }
    public int DesignerId { get; set; }
    public int ImageId { get; set; }
    [Required]
    [MaxLength(250)]
    public string ItemName { get; set; }
    [Required]
    [Range(0,9999)]
    public decimal ItemPrice { get; set; }
    [MaxLength(1000)]
    public string ItemDescription { get; set; }
    [Range(4,22)]
    public int ItemSize { get; set; }
    [Column("CategoryId")]
    public virtual List<Category> Category { get; set; }
    public virtual List<OrderDetail> OrderDetails { get; set; }
    public virtual List<Image> Images { get; set; }
}

图像模型类:将每个图像的URL存储在站点的内容目录中。每个条目可以有多个图像。

public class Image
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ImageId { get; set; }
    [Required]
    public string ImageURL { get; set; }
    [Required]
    public string ItemId { get; set; }
    //Files Being Uploaded by the User
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
    [Column("ItemId")]
    public virtual List<Item> Item { get; set; }
}

门店经理总监

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Item item,HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            //The below successfully saves the file to the content folder when separated into the Index Action.
            foreach (var f in item.Files)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(f.FileName);
                    var path =   Path.Combine(Server.MapPath("~/Content/ItemImages/"+item), fileName);
                    file.SaveAs(path);
                }
            }
    // The below also works when I dont have the Above in the Action.
            db.Items.Add(item);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(item);
    }

创建项目视图

    @model Project.Models.Item
    @{
       ViewBag.Title = "Create";
     }
    <h2>Create</h2>
    @using (Html.BeginForm()) {
       @Html.AntiForgeryToken()
       @Html.ValidationSummary(true)
    <fieldset>
        <legend>Item</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ItemName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ItemName)
            @Html.ValidationMessageFor(model => model.ItemName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ItemPrice)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ItemPrice)
            @Html.ValidationMessageFor(model => model.ItemPrice)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ItemDescription)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ItemDescription)
            @Html.ValidationMessageFor(model => model.ItemDescription)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ItemColour)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ItemColour)
            @Html.ValidationMessageFor(model => model.ItemColour)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ItemSize)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ItemSize)
            @Html.ValidationMessageFor(model => model.ItemSize)
        </div>
        <p>
           <input type="submit" value="Create" />
        </p>
</fieldset>
}
    @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <div>
        <table>
            <tr>
                <td>Files</td>
                <td><input type="file" name="Files" id="Files" multiple/></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="submit" value="Upload" /></td>
            </tr>
        </table>
        </div> 
    }
   <div>
       @Html.ActionLink("Back to List", "Index")
   </div>

在一个步骤中创建项目并为项目添加图像

看起来你已经很接近了。

在将其添加到数据库之前,您只需将图像添加到项目中。

因为你使用的是EF,所以它应该类似于

 //in your action
 //add the images to the item
 item.Images.Add(new Image { ImageUrl = ... });
 //you should be able to just insert the whole entity graph here
 db.Items.Add(item);
 db.SaveChanges();

我想这就是你想要的。

同样在你的模型构造函数中,我认为通常你想初始化这些列表,这样你就不会在做上面的事情时得到空引用异常

public class Item 
{
    public Item()
    {
        this.Images = new List<Image>();
    }
    //...
}