【问题标题】:Create Item and add images for Item in one step一步创建项目并为项目添加图像
【发布时间】:2014-06-30 04:15:46
【问题描述】:

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

我设法让多个文件上传工作,但仅限于 content/Images 文件夹。我想不出将这与项目的创建结合起来,因此您可以在项目的创建过程中将多个图像分配给一个项目。

公平地说,我不知道从这里去哪里,希望能得到任何帮助。

Item Model Class:数据库中的表来存储每个项目。从具有一对多关系的图像表中引用。

 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>

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    所以看起来你已经很接近了。

    您只需将图像添加到项目中,然后再将其添加到数据库中。

    既然你用的是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>();
        }
        //...
    }
    

    【讨论】:

    • 嗨凯尔,感谢您的回复。我遇到的最大问题是视图本身。目前我有一个上传按钮和一个创建按钮。当然我只需要一个按钮,它可以在同一个链接过程中上传和创建?
    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多