我正在尝试上传文件,但它无法按预期工作。我有以下观点:
@using (Ajax.BeginForm("RegisterBand", "NewProfile", new AjaxOptions() { HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
}, new { enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
Bandname
</div>
<div class="col-md-10">
@Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(x => x.BandProfile.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
Genres
</div>
<div class="col-md-10">
@Html.DropDownListFor(x => x.BandProfile.Genres, Enumerable.Empty<SelectListItem>(), new { @class="", multiple = "multiple", style ="width: 100%;"} )
@Html.ValidationMessageFor(x => x.BandProfile.Genres, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
Coverpicture
</div>
<div class="col-md-10">
<input type="file" name="file" id="CoverPicture" />
@Html.ValidationMessageFor(x => x.BandProfile.CoverPicture, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
Description
</div>
<div class="col-md-10">
@Html.EditorFor(x => x.BandProfile.Description, new { htmlAttributes = new { @class = "form-control"} })
@Html.ValidationMessageFor(x => x.BandProfile.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spara" class="btn btn-success" />
</div>
</div>
</div>
}
这是我的控制器:
[HttpPost]
public ActionResult RegisterBand(ProfileViewModel model, HttpPostedFileBase file)
{
if (ModelState.IsValid == false)
{
return Json(JsonRequestBehavior.AllowGet);
}
var bandProfile = _profileService.CreateBandProfile(model.BandProfile, file, UserId);
if (bandProfile != null)
{
userManager.AddToRole(UserId, "Band");
return RedirectToAction("Index", "Welcome");
}
return View("Index");
}
我遇到的问题是file
总是导致null。我不明白为什么。我怎样才能找到问题?
答案 0 :(得分:1)
这里的问题是您使用Ajax.BeginForm()
帮助程序来创建和发布表单。但是,无法使用AJAX上传文件。
您可能需要考虑使用jQuery-based plug-in to accomplish this,它依赖于使用<iframe>
来处理您在幕后的上传操作并将其发布到正确的位置。
否则,您可以考虑使用Html.BeginForm()
尝试使用普通表单,这应该适用于您的方案(如果您不明确需要任何AJAX功能)。
<强>更新强>
此处的另一个问题是,您用于Ajax.BeginForm()
调用的构造函数正在接受AjaxOptions
和htmlAttributes
参数,该参数与此构造函数一样
但是,您当前的使用缺少第三个RouteValues
参数。您可以尝试在其中添加null
,看看是否有任何区别:
@using(Ajax.BeginForm("RegisterBand",
"NewProfile",
null,
new AjaxOptions() {
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace
},
new { enctype = "multipart/form-data"})){
<!-- Content -->
}