我有多個文件上傳Views
與ViewModel
如下結合:與數據註解視圖模型在ASP.NET MVC多文件上傳3
@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);
}
}
問題的解釋 如何定義爲這五個文件上傳輸入控制視圖模型,以便示出了用於相應的驗證錯誤對應的錯誤,如果上載的文件的文件擴展名是不允許的類型。我只有一個查看所有五個文件上傳控件的模型項目。
什麼可以是最好的方式來定義這些多文件上傳控制的視圖模型,以顯示相應的驗證錯誤,而不是用戶嘗試上傳不允許的擴展文件?