2014-02-24 58 views
2

我的模型MVC圖爲byte []

partial class Company 
{ 
    ... More Properties 
    public HttpPostedFileBase FilePicture { get; set; } 
    public byte[] Picture { get; set; } 
} 

我的控制器

[HttpPost] 
public ActionResult Edit(int id, Models.Company model) 
{ 
    if(model.FilePicture != null) 
    { 
     using(Stream inputStream = model.FilePicture.InputStream) 
     { 
      MemoryStream memoryStream = inputStream as MemoryStream; 
      if(memoryStream == null) 
      { 
       memoryStream = new MemoryStream(); 
       inputStream.CopyTo(memoryStream); 
      } 
      model.Picture = memoryStream.ToArray(); 
     } 
    } 
    //EditDefault does the persisting 
    return this.EditDefault(id, model); 
} 

我查看

@using (Html.BeginForm("Edit", currentController, null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    //Clicks on the Picture and the Upload butten are forwarded to the file input tag 
    //readUrl sets the image as sone as the file changes 
    <input id="filePicture" type="file" name="filePicture" onchange="readURL(this);"> 

    <button type="button" id="pictureUploadBtnPicture" onclick="$('#filePicture').click();"> Upload</button> 

    //ClearImg clears the img tag and resets the file input tag 
    <button type="button" id="pictureDeleteBtnPicture" onclick="clearimg(this);"> Delete</button> 

    ...if Picture not null 
    ...{ 
     <img id="PicturePicture" src="data:image/png;base64,@System.Convert.ToBase64String(@Model.Picture.ToArray())"> 

     <input type="hidden" value="@System.Convert.ToBase64String(@Model.Picture.ToArray())" name="Picture"> **added** 
    ...} 
    ...else ... Render empty Picture and set it per javascript 

    <input type="submit" value="Safe" class="btn btn-primary"> 
} 

我有一個包含類似名稱的一些屬性窗體,城市,。 ..和一個包含圖片數據的字節[]。上傳,顯示和刪除正在工作。我現在的問題是,當我改變一些東西,並且我再次安全了網站時,模型中的圖片屬性爲null,我在Post Action中獲得。我想有一些東西與映射無關。

只是想清楚我想img映射到字節[]。

THX提前任何幫助:)

更新:

THX馬特·泰伯;)

增加了一個隱藏的輸入字段,現在我明白了在控制器中。

更新了視圖,以防有人需要它。

回答

1
<img id="Picture" name="Picture" src="data:image/png;base64,@System.Convert.ToBase64String(@Model.Picture.ToArray())"> 

此屬性不是輸入,當您提交此服務器它不會sumbit圖像。你將不得不使用像隱藏輸入存儲字節數組。圖像標記下

嘗試添加該

@Html.HiddenFor(m=>m.Picture)