简体   繁体   English

使用HttpPostedFileBase进行MVC编辑

[英]MVC edit with an HttpPostedFileBase

I have been mostly following this tutorial: http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/ 我主要关注此教程: http : //cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

It created a good create view that allows the user to upload an image. 它创建了一个很好的创建视图,允许用户上传图像。

How would I create a similar page that displays the current image file (such as what this shows when the user has selected one in the create view) and still allows the user to select a different image? 我将如何创建一个类似的页面来显示当前图像文件(例如,当用户在创建视图中选择一个图像文件时显示的页面),并且仍然允许用户选择其他图像?

@model ImageViewModel

<form action="" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        Name:
        @Html.EditorFor(model => model.Name)
    </div>
    <div>
        Image Upload:
        @Html.TextBoxFor(model => model.ImageUpload, new { type = "file" })
    </div>
    <button type="submit">Edit</button>
</form>



public class ImageViewModel
{
    public string Name { get; set; }
    public HttpPostedFileBase ImageUpload { get; set; }
}

As it currently is, this just allows the Name to be changed and a new image to be uploaded. 就目前而言,这仅允许更改名称和上载新图像。 I want it to show the filename of the current image, but I don't know of a way to upload info to the HttpPostedFileBase attribute (database is currently holding the filename/path from create). 我希望它显示当前图像的文件名,但是我不知道将信息上传到HttpPostedFileBase属性的方法(数据库当前保存来自create的文件名/路径)。

Any thoughts would be appreciated. 任何想法将不胜感激。 Thanks. 谢谢。

Add an extra property to your ImageViewModel and bind the current filename to that property: 向您的ImageViewModel添加一个额外的属性,并将当前文件名绑定到该属性:

public class ImageViewModel
{
    public string Name { get; set; }

    public string FileName { get; set; }

    public HttpPostedFileBase ImageUpload { get; set; }
}

In your Edit View just display the FileName property: 在您的“编辑”视图中,仅显示FileName属性:

@model ImageViewModel

<form action="" method="post" enctype="multipart/form-data">

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        Name:
        @Html.EditorFor(model => model.Name)
    </div>
    <div>
        Current uploaded file:
        @Html.DisplayFor(model => model.FileName)
    </div>
    <div>
        Image Upload:
        @Html.TextBoxFor(m => m.ImageUpload, new { type = "file", value = "test" })
    </div>
    <button type="submit">Save</button>

</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM