0
有沒有一種方法可以在mvc中沒有模型的情況下在視圖中驗證純HTML表單?在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
或類似的東西。
但是我沒有在我的視圖中使用任何模型:(。它會引用什麼? –
那麼,兄弟,它可能是時間開始使用一個。在你的情況下,我可以看到3個輸入字段:一些文件輸入,文本輸入和一個文本區域,這自動意味着一個有3個屬性的視圖模型,第一個是'HttpPostedFileBase'類型,另外兩個是字符串類型,然後你可以用第一個數據註解來修飾第一個數據註解,比如'[Required ]'以確保用戶已經選擇了一個文件或者其他東西,我不知道你的要求,很難說,但你明白了,然後在你看來,這只是使用強類型幫助器的問題。 –