我正在尝试上传一个文件,但它不能像预期的那样工作。我有以下的看法:
@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。我不明白为什么。如何找到问题所在?
发布于 2016-04-06 22:22:53
这里的问题是您正在使用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 -->
}https://stackoverflow.com/questions/36453792
复制相似问题