MVC5 Razor 上传图片

MVC5 Razor Upload Image

我正在尝试创建一个页面,在编辑 "Asset" 用户可以在部分视图中上传图片。

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

因此,当用户提交编辑页面时,更改的详细信息以及新的闪亮图片 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) 页面,更不用说能够查看是否发送整个编辑作品。

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

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

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