【问题标题】:MVC5 Razor Upload ImageMVC5 剃刀上传图片
【发布时间】:2017-02-21 09:36:49
【问题描述】:

我正在尝试创建一个页面,在编辑“资产”时,用户可以在部分视图中上传图片。

在提交图片时,出于显而易见的原因,我希望将文件名保存到服务器位置并以其资产 ID 号为前缀,然后返回部分视图但包含图片。

因此,当用户提交编辑页面时,更改的详细信息以及新的闪亮图片 url 都会保存到数据库中。

这是我目前所拥有的。

编辑视图 (Edit.cshtml)

@model Asset_Manager.DB.Asset

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Asset</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Aid)
        **** other fields
        <div class="form-group">
            @Html.LabelFor(model => model.Picture_Location, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.Partial("~/Views/Asset/UploadAssetImage.cshtml",Model)
            </div>
        </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

部分上传视图 (UploadAssetImage.cshtml)

@model Asset_Manager.DB.Asset

@using (Html.BeginForm("UploadPicture", "Asset", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <img src="@Model.Picture_Location" alt="@Model.Description" width="250" height="250" /><br />
    <input type="file" name="file" />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
    <input type="hidden" name="id" value="@Model.Aid" />
}

最后是控制器方法(AssetController.cs

[HttpPost]
public ActionResult UploadPicture(int id,FormCollection collection)
{
    if (Request.Files.Count > 0)
    {
        var file = Request.Files[0];

        if (file != null && file.ContentLength > 0)
        {
            var fileName = "Asset_" + id + "_" + Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/AssetImages/"), fileName);
            file.SaveAs(path);
        }
    }

    Asset A = new Asset();

    A = _dal.GetAssetByID(id);


    return PartialView("UploadAssetImage", A.Aid);

}

现在我的问题

每次我尝试提交照片时,我都会被直接踢到资产索引 (Index.cshtml) 页面,更不用说能够查看发送整个编辑是否有效。

控制器方法下的断点也没有触发,所以我无法追踪问题可能出在哪里。

任何帮助/示例/正确方向的指针将不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc razor partial-views image-uploading


    【解决方案1】:

    您的表单中有一个表单,它是无效的 HTML。最外面的表单是提交的内容,重要的是,此表单不包含enctype="multipart/form-data" 属性。将该属性添加到视图中的表单并删除部分表单。

    【讨论】:

    • 感谢 chris,让事件触发并将文件保存在服务器上,但在提交之前没有显示图片,或者这需要一些 JS 脚本吗?
    • 是的,这需要 JS,特别是 File API。
    猜你喜欢
    • 2019-04-05
    • 2014-03-04
    • 2016-03-04
    • 1970-01-01
    • 2013-03-18
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多