C# @Html.EditorFor(图像)
我正试图允许用户上传一个图像到我们的网站,我不太清楚如何使用这个。我尝试使用多种类型来定义图像,包括C# @Html.EditorFor(图像),c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我正试图允许用户上传一个图像到我们的网站,我不太清楚如何使用这个。我尝试使用多种类型来定义图像,包括System.Drawing.image和HttpPostedFileWrapper,但是@Html.EditorFor总是(可以理解)将其属性作为字段进行编辑 在我看来,我确实有,而不是@Html.EditorFor,我确实有,但它没有作为模型的一部分进入我的视图?我是MVC的新手,所以我希望这是一件小事 以下是我的看法: @using (Html.BeginForm()) { @Htm
System.Drawing.image
和HttpPostedFileWrapper
,但是@Html.EditorFor
总是(可以理解)将其属性作为字段进行编辑
在我看来,我确实有,而不是@Html.EditorFor
,我确实有
,但它没有作为模型的一部分进入我的视图?我是MVC的新手,所以我希望这是一件小事
以下是我的看法:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>New Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
<input type="file" name="imageToUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
确保在表单上指定正确的enctype=“multipart/form data”
,否则您将无法上载文件:
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>New Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ImageToUpload)
</div>
<div class="editor-field">
<input type="file" name="imageToUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
然后为HttpPostedFileBase
类型定义一个自定义编辑器模板(请参见下文,您需要修改模型以实际使用此类型)。因此,~/Views/Shared/EditorTemplates/HttpPostedFileBase.cshtml
中的编辑器模板:
@model HttpPostedFileBase
@Html.TextBox("", null, new { type = "file" })
在视图模型上,使用HttpPostedFileBase
类型,并确保属性名称与表单上输入的文件名称匹配:
public class ImageEditViewModel
{
public int CollectionId { get; set; }
public string Description { get; set; }
public HttpPostedFileBase ImageToUpload { get; set; }
public int Order { get; set; }
}
还要确保签出。a big+1,enctype很容易成为最常被遗忘的东西之一。是的,刚刚在视图中看到,我将其命名为imageToUpload,但应该是imageToUpload。非常感谢
<div class="editor-label">
@Html.LabelFor(model => model.ImageToUpload)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ImageToUpload)
</div>
@model HttpPostedFileBase
@Html.TextBox("", null, new { type = "file" })
public class ImageEditViewModel
{
public int CollectionId { get; set; }
public string Description { get; set; }
public HttpPostedFileBase ImageToUpload { get; set; }
public int Order { get; set; }
}