有没有办法在 mvc 中没有模型的视图中验证纯 HTML 表单?
我的观点看起来像
@using (Html.BeginForm("Upload", "Picture", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<a class="uploadlink" style="cursor:pointer" onclick="document.getElementById('file').click();">Open</a>
<input type="file" name="file" id="file" style="opacity:0" onchange="document.getElementById('title').value = this.value.substring(this.value.lastIndexOf('\\') +1 );"/>
<br />
<input type="text" name="title" id="title" />
<br/>
<textarea name="desc" id="desc"></textarea>
<br/>
<input type="submit" value="Save" />
}
我的控制器看起来像
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(string title, string desc, HttpPostedFileBase file)
{
if (file == null)
{
return Content("<span id='result'>Please select a file first</span>");
}
if (string.IsNullOrEmpty(title))
{
return Content("<span id='result'>Please enter a name</span>");
}
if (file.ContentLength > 0)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
string c = file.FileName.Substring(file.FileName.LastIndexOf("."));
title = title.Replace(c, "");
byte[] uploadedFile = new byte[file.InputStream.Length];
file.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
try
{
using (MemoryStream ms = new MemoryStream(uploadedFile))
Image.FromStream(ms);
}
catch (ArgumentException)
{
return Content("<span id='result'>The file you are trying to upload is not a valid image file.</span>");
}
而不是return Content
我想知道是否有任何方法可以添加ModelState.AddError
或类似的东西。