2013-08-28 41 views
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或類似的東西。

回答

1

是的,你可以添加ModelState.AddModelError但在你看來,如果你想顯示此消息,你應該使用一些HTML傭工如Html.ValidationSummaryHtml.ValidationMessage的。

例如,在您的視圖:

<input type="file" name="file" id="file" style="opacity:0" onchange="document.getElementById('title').value = this.value.substring(this.value.lastIndexOf('\\') +1);"/> 
@Html.ValidationMessage("file") 

,並在你的控制器動作:

ModelState.AddModelError("file", "some error message"); 

顯然,這是更好的使用視圖模型,這些傭工的強類型的等價物以及使用幫助者生成你的標記,而不是像你的情況那樣對它進行硬編碼。

你知道,事情就是:

public class MyViewModel 
{ 
    [Required(ErrorMessage = "Please select a file first")] 
    public HttpPostedFileBase File { get; set; } 

    [Required(ErrorMessage = "Please enter a name")] 
    public string Title { get; set; } 

    public string Description { get; set; } 
} 

,並在您看來的東西,如:

@model MyViewModel 
... 

@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> 

    @Html.TextBoxFor(x => x.File, new { 
     type = "file", 
     style = "opacity:0", 
     onchange="document.getElementById('title').value = this.value.substring(this.value.lastIndexOf('\\') +1);" 
    }) 
    @Html.ValidationMessageFor(x => x.File) 
    <br /> 

    @Html.EditorFor(x => x.Title) 
    @Html.ValidationMessageFor(x => x.Title) 
    <br/> 

    @Html.TextAreaFor(x => x.Description) 
    <br/> 

    <input type="submit" value="Save" /> 
} 

,並在你的控制器動作:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Upload(MyViewModel model) 
{ 
    if (!ModelState.IsValid)  
    { 
     return View(model); 
    } 

    try 
    { 
     Image.FromStream(model.File.InputStream); 
    } 
    catch (ArgumentException) 
    { 
     ModelState.AddModelError("File", "The file you are trying to upload is not a valid image file."); 
    } 

    // At this stage you know that the model is valid => 
    // you could do something with those model.Title and model.Description properties 

    return RedirectToAction("Success"); 
} 

通過你可能採取的方式看看following answer of mine從你的控制器動作中刪除更多管道/驗證代碼不屬於那裏。

+0

但是我沒有在我的視圖中使用任何模型:(。它會引用什麼? –

+0

那麼,兄弟,它可能是時間開始使用一個。在你的情況下,我可以看到3個輸入字段:一些文件輸入,文本輸入和一個文本區域,這自動意味着一個有3個屬性的視圖模型,第一個是'HttpPostedFileBase'類型,另外兩個是字符串類型,然後你可以用第一個數據註解來修飾第一個數據註解,比如'[Required ]'以確保用戶已經選擇了一個文件或者其他東西,我不知道你的要求,很難說,但你明白了,然後在你看來,這只是使用強類型幫助器的問題。 –