我正在使用ASP.NET MVC 5并拥有这个简单的ViewModel。
public class ArtistVM
{
public string FName { get; set; }
public string LName { get; set; }
public HttpPostedFileBase ImgUpload { get; set; }
}
我知道我需要HttpPostedFileBase
的自定义编辑器模板,所以我已经将HttpPostedFileBase.cshtml
添加到~/Views/Shared/EditorTemplates/
里面,我有以下内容:
@model HttpPostedFileBase
@Html.TextBoxFor(model => model, new { type = "file" })
就显示类型文件的输入而言,这似乎工作正常!
问题出现在发布和绑定时,我的ImgUpload
属性总是返回null,这告诉我在编辑模板中有些不对。
新艺术家视图的代码如下所示:
@using (Html.BeginForm("New", "Artist", FormMethod.Post, new { encrypt = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImgUpload, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImgUpload, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImgUpload, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Artist" class="btn btn-primary" />
</div>
</div>
</div>
}
处理帖子的Controller Action是:
[HttpPost]
public ActionResult New(ArtistNewVM vm)
{
var validImageTypes = new string[]
{
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png"
};
if (vm.ImgUpload == null || vm.ImgUpload.ContentLength == 0)
{
// ** gets inside here **
ModelState.AddModelError("ImageUpload", "This field is required");
}
else if (!validImageTypes.Any(vm.ImgUpload.ContentType.Contains))
{
ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
}
if (ModelState.IsValid)
{
// do the magic
}
return View(vm);
}
答案 0 :(得分:2)
您的表单中的html属性有误enctype
代表&#34;编码类型&#34; 不是encrypt
see here
enctype
属性的目的是指示在将表单数据发送到action属性中定义的位置之前应如何编码表单数据。
变化:
new { encrypt = "multipart/form-data"}
为:
new { enctype = "multipart/form-data"}