这是我的控制器代码以及我的视图:
@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" })) {
@Html.ValidationSummary()
<div class="form-field">
<p>@Html.LabelFor(m => m.Name)</p>
@Html.EditorFor(m => m.Name)
</div>
<div class="form-field">
<p>@Html.LabelFor(m => m.Description)</p>
@Html.EditorFor(m => m.Description)
</div>
<div class="form-field">
<p>@Html.LabelFor(m => m.UnitPrice)</p>
@Html.EditorFor(m => m.UnitPrice)
</div>
<div class="form-field">
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
</div>
<div class="form-field">
<input type="submit" value="Create" />
</div>
}
在控制器中。不要只关注动作方法的内容,只关注类型List<HttpPostedFileBase>
的参数。这是正确的做事方式吗?事实上,images
在提交表格时为空。
[HttpPost]
public ActionResult Create(ProductModel model, List<HttpPostedFileBase> images)
{
try
{
if (ModelState.IsValid)
{
var newProduct = Mapper.Map<ProductModel, Product>(model);
_productRepository.CreateProduct(newProduct);
_productRepository.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View(model);
}
}
如果你能提供一个非常简单的例子,那就太棒了。
答案 0 :(得分:6)
好的,所以这是一个如何做的简单示例。最终结果:
HTML标记是一个简单的表单,带有提交按钮。
@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" })) {
@Html.ValidationSummary()
<div class="form-field">
<p>Select pictures:</p>
<div class="upload-container">
<div class="upload">
<input type="file" name="files" id="file1" />
<img src="@Url.Content("~/Public/images/delete.png")" alt="Remove picture." />
</div>
</div>
</div>
<div class="form-field">
<input type="submit" value="Create" />
</div>
}
我们还需要一些jQuery魔术,这样每次有人添加图像时,我们都会让它们根据需要添加更多。用户可以上传N个图像。
<script type="text/javascript">
$(document).ready(function () {
var currentImage = 1;
$("body").on("change", "input[name='files']", function () {
var pathToRemoveIcon = "@Url.Content("~/Public/images/delete.png")";
currentImage = currentImage + 1;
var htmlToAppend = '<div class="upload"><input type="file" name="files" id="file' + currentImage + '" /><img src="' + pathToRemoveIcon + '" alt="Remove picture." /></div>';
$('.upload-container').append(htmlToAppend);
}).on("click", ".upload img", function () {
if ($(this).parent().siblings().length > 0) {
$(this).parent().remove();
}
});
});
</script>
最后是控制器代码:
[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
try
{
if (ModelState.IsValid)
{
//Persist the files uploaded.
}
return RedirectToAction("Index");
}
catch
{
return View(model);
}
}
答案 1 :(得分:1)