與MVC

2015-07-10 26 views
4

顯示形式錯誤我有一個上傳的圖像文件,並檢查他們的JPG文件形式:與MVC

// CarAdmin/Index.cshtml 
@model MySite.Models.Car 
@using (Html.BeginForm("CarImageUpload", "Car", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="file" /> 
    <input type="text" name="imageInfo" /> 
    <input type="submit" value="OK" /> 
} 
<form action="CarAJAX" method="post" name="CarAdminForm"> 
    <input name="Make" value="@Model.Name/> 
    <input type="submit" value="Update Car Info"> 
</form> 

// CarController.cs 
[HttpPost] 
public ActionResult CarImageUpload(HttpPostedFileBase file) 
{ 
    ValidateImageFile V = new ValidateImageFile(file); // checks that the file is a jpg 
    List<String> Validity = V.Issues; 

    if (Validity.Count == 0) 
    { 
     file.SaveAs(V.FilePath); 
    } 
    else 
    { 
     Response.Write(String.Join("<br>", Validity.ToArray()); // THIS IS PROBLY WRONG 
    } 
    RedirectToAction("CarAdmin"); 
} 
public ActionResult CarAdmin() 
{ 
    return View("CarAdmin/Index.cshtml"); 
} 

如果ValidateImageFile類發現一個問題,我想:

  • 給予輸入端,有一個問題一類
  • 在頁面上顯示的消息

不過,我不知道如何操作Controller中的表單,並且我的Response.Write不發送任何東西(我可以看到 - 但我不知道如何訪問它)。

我對如何做到這一點有一些想法,但它們看起來像是膠帶作業,而不是最佳實踐。

回答

2

用戶Darian Dimitrov回答了一個與您的問題非常相似的問題,他的解決方案應該指向正確的方向。

Is there a way to validate incoming HttpPostedFilebase files in MVC 2?

另一個很好的資源爲你的正在試圖做的是:

http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

你的觀點可能看起來像:

// CarAdmin/Index.cshtml 
@model MySite.Models.CarUploadViewModel 
@using (Html.BeginForm("CarImageUpload", "Car", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="ImageUpload" /> 
    <input type="text" name="ImageInfo" /> 
    <input type="submit" value="OK" /> 
} 
<form action="CarAJAX" method="post" name="CarAdminForm"> 
    <input name="Make" value="@Model.Name/> 
    <input type="submit" value="Update Car Info"> 
</form> 

你的模型可能看起來像:

public class CarUploadViewModel 
{ 
    [Required] 
    public string ImageInfo{ get; set; } 

    [DataType(DataType.Upload)] 
    HttpPostedFileBase ImageUpload { get; set; } 
} 

你的控制器可能看起來像:

[HttpPost] 
public ActionResult CarImageUpload(CarUploadViewModel model) 
{ 
    ValidateImageFile validity = new ValidateImageFile(model.ImageUpload); // checks that the file is a jpg 
    List<String> issues = validity.Issues; 

    if (issues.Count > 0) 
    { 
     // TODO: Add more descriptive issue messages 
     ModelState.AddModelError("ImageUpload", "There was an issue."); 
    } 

    if(ModelState.IsValid) 
    { 
     model.ImageUpload.SaveAs(V.FilePath); 
     RedirectToAction("CarAdmin"); 
    } 

    return View(model); 
} 

基本上,你想要做什麼是創建表單模型,檢查它的有效性,如果它是不是有效,返回驗證錯誤的模型視圖。

要添加自定義錯誤的模型,你可以使用:

ModelState.AddModelError("MyField", "Custom error message here"); 

,並輸出到視圖,如:

@Html.ValidationMessage("MyField"); 
+0

謝謝,你覺得你能告訴一個例子嗎?我對這個模型看起來有點困惑。 –

+0

我已添加其他資源並更新了我的答案。請記住,我沒有編譯器,所以它可能不是100%,但這應該有助於:) –

+0

哦,這太棒了,它讓我很想念。 –