2013-07-15 28 views
0

我正在使用Jasny Fileupload來添加圖像並將其更新爲文章。當用戶添加或編輯文章時,一切正常,除非用戶選擇使用現有圖像編輯文章,但不會更改或刪除圖像。ASP.NET MVC Jasny如何在編輯操作中檢查現有文件

基本上我的文件輸入在這個實例中是空的,所以我現在的代碼假設用戶已經刪除了圖像並相應地設置了模型屬性。

在我的控制器我有以下幾點:

if (file != null) 
{ 
    var fileName = Guid.NewGuid().ToString() + Path.GetFileName(file.FileName); 
    var path = Path.Combine(Server.MapPath("/Content/ArticleImages"), fileName); 
    file.SaveAs(path); 
    articleToUpdate.ImagePath = fileName; 
} 
else 
{ 
    articleToUpdate.ImagePath = null; 
} 

我的觀點:

@if (Model.article.ImagePath == null) 
{ 
    <div class="fileupload fileupload-new" data-provides="fileupload"> 
     <div class="fileupload-preview thumbnail" style="width: 200px; height: 150px; margin-top: 10px"> 
     </div> 
     <div> 
      <span class="btn btn-file"><span class="fileupload-new">Select image</span><span 
       class="fileupload-exists">Change</span><input type="file" name="file" /></span> 
      <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a> 
     </div> 
    </div> 
} 
else 
{ 
    <div class="fileupload fileupload-exists" data-provides="fileupload"> 
     <div class="fileupload-preview thumbnail" style="width: 200px; height: 150px; margin-top: 10px"> 
      <img src="/Content/ArticleImages/@Model.article.ImagePath"/> 
     </div> 
     <div> 
      <span class="btn btn-file"><span class="fileupload-new">Select image</span><span 
       class="fileupload-exists">Change</span><input type="file" name="file" /></span> 
      <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a> 
     </div> 
    </div> 
} 

我怎麼能在我的位指示,請檢查用戶是否已經沒有modiied的形象,反對刪除或更改它?

回答

1

在您的視圖中添加一個隱藏字段,該字段顯示了您的viewmodel的一個屬性,指示您的圖像的存在。

查看

@Html.HiddenFor(model => model.HasImage) 

視圖模型

public bool HasImage 
{ 
    get { return !string.IsNullOrEmpty(this.ImagePath); } 
} 
在控制器

現在

if (file != null) 
{ 
    // Save your Image 
} 
else if (!model.HasImage) 
{ 
    articleToUpdate.ImagePath = null; 
} 

您可能需要一個按鈕/ JavaScript添加到您的視圖,以便用戶可以刪除和更改隱藏字段的值爲HasImage