我是MVC和网络编程的新手。
我的上传图片工作正常,但是当我使用几乎完全相同的代码来允许用户修改其上传时,它的HttpPostedFileBase始终为null。让我疯狂......
这是模型 公共类ModifyGenreViewModel { public int Id {get;组; }
[Display(Name = "Nom du style")]
public string Name { get; set; }
[Display(Name = "Image")]
public HttpPostedFileBase Image { get; set; }
}
和视图
@using (Html.BeginForm("ModifyGenre", "Upload", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>@Resource.StyleCreationHeader</h4>
<hr />
@Html.ValidationMessageFor(model=>Model)
<div class="form-group" style="display:none">
@Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Image, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" data-val="true" id="ModifyGenreViewModel_Image" name="ModifyGenreViewModel.Image" />
@Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="@Resource.Modify" class="btn btn-primary" />
</div>
</div>
</div>
}
当我在控制器中设置断点时,我会看到Id和名称,但Image始终为null。
感谢您的帮助!
答案 0 :(得分:2)
文件输入的name属性值应与视图模型属性名称匹配,以使模型绑定正常工作。
将输入字段名称更改为"Image"
<input type="file" data-val="true" id="ModifyGenreViewModel_Image" name="Image" />
假设您的HttpPost操作方法接受ModifyGenreViewModel
对象作为参数。
[HttpPost]
public ActionResult ModifyGenre(ModifyGenreViewModel model)
{
// to do : return something
}