我有多个文件上传Views
,ViewModel
绑定如下:
@model IVRControlPanel.Models.UploadNewsModel
@using (Html.BeginForm("index", "NewsUpload", FormMethod.Post, new { name = "form1", @id = "form1" }))
{
@Html.ValidationSummary(true)
<div class="field fullwidth">
<label for="text-input-normal">
@Html.Label("Select Active Date Time")</label>
<input type="text" id="active" value="@DateTime.Now" />
@Html.ValidationMessageFor(model => model.ActiveDateTime)
</div>
<div class="field fullwidth">
<label>
@Html.Label("Select Language")
</label>
@Html.DropDownList("Language", (SelectList)ViewBag.lang)
</div>
<div class="field">
<label>
@Html.Label("General News")
</label>
@Html.TextBoxFor(model => model.generalnews, new { name = "files", @class="custom-file-input", type = "file" })
@Html.ValidationMessageFor(model => model.generalnews)
</div>
<div class="field">
<label>
@Html.Label("Sports News")
</label>
@Html.TextBoxFor(model => model.sportsnews, new { name = "files", @class = "custom-file-input", type = "file" })
@Html.ValidationMessageFor(model => model.sportsnews)
</div>
<div class="field">
<label>
@Html.Label("Business News")
</label>
@Html.TextBoxFor(model => model.businessnews, new { name = "files", @class = "custom-file-input", type = "file" })
@Html.ValidationMessageFor(model => model.businessnews)
</div>
<div class="field">
<label>
@Html.Label("International News")
</label>
@Html.TextBoxFor(model => model.internationalnews, new { name = "files", @class = "custom-file-input", type = "file" })
@Html.ValidationMessageFor(model => model.internationalnews)
</div>
<div class="field">
<label>
@Html.Label("Entertaintment News")
</label>
@Html.TextBoxFor(model => model.entertaintmentnews, new { name = "files", @class = "custom-file-input", type = "file" })
@Html.ValidationMessageFor(model => model.entertaintmentnews)
</div>
<footer class="pane">
<input type="submit" class="bt blue" value="Submit" />
</footer>
}
带有数据注释的视图模型,用于验证允许扩展的文件上传,如下所示:
public class UploadNewsModel
{
public DateTime ActiveDateTime { get; set; }
// public IEnumerable<SelectListItem> Language { get; set; }
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf", ".wav" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase files { get; set; }
}
控制器:用于保存多个文件并在存在错误时返回视图
[HttpPost]
public ActionResult Index(UploadNewsModel news, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var serverpath = Server.MapPath("~/App_Data/uploads/News");
var path = Path.Combine(serverpath, fileName);
if (!Directory.Exists(serverpath))
{
Directory.CreateDirectory(serverpath);
}
file.SaveAs(path);
}
}
}
return View(news);
}
}
问题说明 如何为这五个文件上传输入控件定义视图模型,以便在不允许上传文件的文件扩展名类型时显示相应的错误以显示相应的验证错误。对于所有五个文件上传控件,我只有一个视图模型项。
为那些显示各自验证错误的多个文件上传控件定义视图模型的最佳方法是什么,而不是用户尝试上传不允许扩展名的文件???