如何用新上传的图片替换旧图片

时间:2019-02-13 19:44:26

标签: c# asp.net-mvc

我正在尝试创建一个页面,用户可以在其中编辑图像详细信息(例如图像详细信息)并上传新图像来代替旧图像。当用户上传新图像时,旧图像应替换为新图像。我可以编辑image_detail,但不能用新图像替换旧图像。每次我上传新图像时,新图像URL都将变为null。我在代码中错过了什么?

查看:

@using System.Configuration
@model List<Records.Models.Image>

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
<div >
    @Html.ValidationSummary(true)
    @for (i = 0; i < Model.Count; i++)
    {
        @Html.HiddenFor(model => model[i].id)

        <div class="form-group">
            <div class="control-label col-md-2">
                <label for="file" class="medialabel">Image</label>
            </div>

            <div class="col-md-2">
                <img src="@Html.DisplayFor(model => model[i].url)" style="width:100px; height:100px;" />
                @Html.ValidationMessageFor(model => model[i].url)
                <label for="file" class="medialabel required">Upload New File</label>
                <input type="file" name="newimage" id="newimage" multiple="multiple" />
            </div>
            @Html.LabelFor(model => model[i].image_detail, new
            {
                @class = "control-label col-md-2 medialabel"
            })
            <div class="col-md-2">
                @Html.TextBoxFor(model => model[i].image_detail)
                @Html.ValidationMessageFor(model => model[i].image_detail)
            </div>
        </div>
    }
    <div class="form-group">
        <input type="submit" value="Save" class="roundRect blueGradient" />
    </div>
</div>

}

控制器:

[HttpPost]
    public ActionResult Edit(int id, List<Image> images, HttpPostedFileBase newimage)
    {
        if (ModelState.IsValid)
        {

            foreach (var image in images)
            {

                if (image.id != 0 )
                {
                    if (!string.IsNullOrEmpty(images.image_detail) && (image.newimage != null))
                    {
                        _db.Entry(image).State = EntityState.Modified;
                        _db.SaveChanges();
                        return RedirectToAction("Index", new { id = image.id });

                    }
                    else
                    {
                        _db.Images.Remove(image);
                        _db.SaveChanges();
                        return RedirectToAction("Index", new { id = image.id });
                    }

                }
                else
                {
                    if (!string.IsNullOrEmpty(image.image_detail))
                    {
                        _db.Images.Add(image);
                        _db.SaveChanges();
                        return RedirectToAction("Index", new { id = image.id });
                    }

                }
            }
        }
        return View(images);
    }

0 个答案:

没有答案