作为文件上传 (ASP.NET MVC3) 的一部分,将 id 和 enctype 属性添加到 HTML.BeginForm 将 HttpPostedFileBase 返回为 null
模型:
public class ProfileModel
{
[UIHint("Upload")]
public HttpPostedFileBase ImageUpload { get; set; }
}`
ProfileForm.cshtml
@using (Html.BeginForm("Update", "Profile", new { ProfileId = ViewBag.ProfileID }, FormMethod.Post, new { @enctype = "multipart/form-data", @id = "ProfileForm" }))
{
<div>
@Html.LabelFor(model => Model.ImageUpload)
@Html.TextBoxFor(model => Model.ImageUpload, new { type = "file" })
</div>
<div class='buttons'>
<input type="submit" value='Save' />
</div>
}
控制器
public Upload(ProfileModel viewModel)
{
if (viewModel.ImageUpload != null && viewModel.ImageUpload.ContentLength > 0)
{
var uploadDir = "~/uploads";
var imagePath = Path.Combine(Server.MapPath(uploadDir), viewModel.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, viewModel.ImageUpload.FileName);
viewModel.ImageUpload.SaveAs(imagePath);
}
}
如果我删除如下@id = "ProfileForm"
属性,我将获得 HttpPostedFileBase (ImageUpload) 值。
@using (Html.BeginForm("Update", "Profile", new { ProfileId = ViewBag.ProfileID }, FormMethod.Post, new { @enctype = "multipart/form-data"}))
{ }
我需要同时传递 id 和 enctype - 谁能告诉我我做错了什么或者有更好的方法吗?