2012-09-16 46 views
1

我目前在MVC3中構建我的第一個應用程序。在我的一個觀點中,有兩種形式。一個是隻選擇一個圖像,並使用AJAX在頁面上顯示/上傳(調用另一個控制器並使用隱藏的IFrame,如post)。另一種形式是輸入名稱,地址等信息。另外,當使用第一種形式選擇和導入圖像時,會在第二種形式中填充隱藏字段,以便在調用Create控制器時創建所有內容在數據庫中。MVC3中的兩種形式會導致不需要的刷新

所有這些都可以很好地工作,但如果用戶犯了一個錯誤,並在第二個表單的數字字段中輸入文本,我的模型的驗證就會得到保證,並且會有一個回顯顯示紅色的錯誤。通過這樣做,第一種形式會丟失所有信息,並通過文件輸入控件重新設置,並且不顯示圖像。

有沒有人有一個想法如何解決這個問題?我對MVC3和AJAX都很陌生,所以也許我做錯了什麼。

我的最終目標是,一旦圖片顯示在頁面上(並上傳),它會一直保持到第二個表單被驗證併發送到我的創建控制器。

謝謝!

編輯: 有些人要求代碼,在這裏! 這是視圖:

@model RecettesMaison.Models.Recipe 

@{ 
    ViewBag.Title = "Create"; 
} 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js" type="text/javascript"></script> 

<script type="text/javascript"> 
    var isFirstLoad = true; 
    var loadingImg; 

    function UploadImage() { 
     var fileUploader = document.getElementById("fileuploader"); 
     $(fileUploader).hide(); 

     //Create a new image and insert it into the Images div. Just to be fancy, 
     //we're going to use a "FadeIn" effect from jQuery 
     var imgDiv = document.getElementById("Images"); 
     loadingImg = new Image(); 
     loadingImg.src = "../../Pictures/ajax-loader.gif"; 

     //Hide the image before adding to the DOM 
     $(loadingImg).hide(); 
     imgDiv.appendChild(loadingImg); 
     //Now fade the image in 
     $(loadingImg).fadeIn(500, null); 

     $("#ImgForm").submit(); 
    } 

    function UploadImage_Complete() { 
     //Check to see if this is the first load of the iFrame 
     if (isFirstLoad == true) { 
      isFirstLoad = false; 
      return; 
     } 

     //Reset the image form so the file won't get uploaded again 
     document.getElementById("ImgForm").reset(); 

     //Grab the content of the textarea we named jsonResult . This shold be loaded into 
     //the hidden iFrame. 
     var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML); 

     //If there was an error, display it to the user 
     if (newImg.IsValid == false) { 
      alert(newImg.Message); 
      return; 
     } 

     //Create a new image and insert it into the Images div. Just to be fancy, 
     //we're going to use a "FadeIn" effect from jQuery 
     var imgDiv = document.getElementById("Images"); 
     var img = new Image(); 
     img.src = newImg.ImagePath; 
     img.name = "uploadedImage"; 


     var input = document.createElement("input"); 
     input.setAttribute("type", "hidden"); 
     input.setAttribute("name", "Picture"); 
     input.setAttribute("id", "Picture"); 
     input.setAttribute("value", newImg.RealName); 
     document.getElementById("Hidden").appendChild(input); 

     //Hide the image before adding to the DOM 
     $(img).hide(); 
     imgDiv.removeChild(loadingImg) 
     imgDiv.appendChild(img); 
     $(img).addClass('img-polaroid'); 

     //Now fade the image in 
     $(img).fadeIn(500, null); 
    } 
</script> 

<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute; left: -999em; top: -999em;"></iframe> 
    <fieldset> 
     <div class="row-fluid"> 
      <div class="span12"> 
      <h4>Publier une recette</h4> 
      <div class="row-fluid"> 
       <div class="span3"> 

       @using (Html.BeginForm("UploadImage", "Recipe", FormMethod.Post, 
        new 
        { 
         enctype = "multipart/form-data", 
         id = "ImgForm", 
         name = "ImgForm", 
         target = "UploadTarget" 
        })) 
       { 
        <div id="fileuploader"> 
        <input id="lefile" type="file" style="display:none" name="imageFile" accept="image/x-png, image/jpeg" /> 
        <div class="input-append"> 
         <input id="photoCover" class="input-large" type="text" /> 
         <a class="btn" onclick="$('input[id=lefile]').click();">Parcourir...</a> 
        </div> 

        <script type="text/javascript"> 
         $('input[id=lefile]').change(function() { 
          $('#photoCover').val($(this).val()); 
         }); 
        </script> 
        <input type="button" class="btn btn-success" value="Sauvegarder l'image" onclick="UploadImage()" /> 
        </div> 

        <div id="Images"></div> 
       } 
       </div> 
       <div class="span9"> 
       @using (Html.BeginForm("Create", "Recipe", FormMethod.Post, new { id = "realForm", name = "realform" })) 
       { 
       @Html.ValidationSummary(true) 
       <div id="Hidden"></div> 
       <div class="editor-label"> 
        @Html.LabelFor(model => model.RecipeName) <div class="alert alert-info">Soyez original!</div> 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.RecipeName) 
        @Html.ValidationMessageFor(model => model.RecipeName) 
       </div> 

       <div class="editor-label"> 
        @Html.LabelFor(model => model.Source) <div class="alert alert-info">(Exemple: Ricardo, Food Channel, Blog de Jean Cuisine, etc...)</div> 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.Source) 
        @Html.ValidationMessageFor(model => model.Source) 
       </div> 

       <div class="editor-label"> 
        @Html.LabelFor(model => model.PreparationTime) 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.PreparationTime) minutes 
        @Html.ValidationMessageFor(model => model.PreparationTime) 
       </div> 

       <div class="editor-label"> 
        @Html.LabelFor(model => model.CookingTime) 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.CookingTime) minutes 
        @Html.ValidationMessageFor(model => model.CookingTime) 
       </div> 

       <div class="editor-label"> 
        @Html.LabelFor(model => model.MacerationTime) 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.MacerationTime) minutes 
        @Html.ValidationMessageFor(model => model.MacerationTime) 
       </div> 

       <div class="editor-label"> 
        @Html.LabelFor(model => model.Portions) <div class="alert alert-info">Combien d'adultes cette recettes peut nourir?</div> 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.Portions) 
        @Html.ValidationMessageFor(model => model.Portions) 
       </div> 

       <div class="editor-label"> 
        @Html.LabelFor(model => model.Commentary) <div class="alert alert-info">Partagez votre expérience avec cette recette, que ce soit au moment de sa création ou de sa préparation. <br />Dites les modifications que vous faites à la recette originale.<br />Rendez cette recettes personnelle! </div> 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => model.Commentary) 
        @Html.ValidationMessageFor(model => model.Commentary) 
       </div> 
       <p> 
        <input type="submit" class="btn btn-success" value="Publier la recette!" /> 
       </p> 
       } 
       </div> 
      </div> 
      </div> 
     </div> 
    </fieldset> 

下面是圖像

[HttpPost] 
public WrappedJsonResult UploadImage(HttpPostedFileWrapper imageFile) 
{ 

    if (imageFile == null || imageFile.ContentLength == 0) 
    { 
     return new WrappedJsonResult 
     { 
      Data = new 
      { 
       IsValid = false, 
       Message = "No file was uploaded.", 
       ImagePath = string.Empty 
      } 
     }; 
    } 

    if (imageFile.ContentType != "image/jpeg" && imageFile.ContentType != "image/png") 
    { 
     return new WrappedJsonResult 
     { 
      Data = new 
      { 
       IsValid = false, 
       Message = "Mauvais format de fichier!", 
       ImagePath = string.Empty 
      } 
     }; 
    } 

    int nIndexPoint = imageFile.FileName.IndexOf("."); 
    string strExtension = imageFile.FileName.Substring(nIndexPoint + 1); 

    var fileName = String.Format("{0}.{1}", Guid.NewGuid().ToString(), strExtension); 

    var imagePathFull = Path.Combine(Server.MapPath(Url.Content("~/Pictures/Upload/FullSize")), fileName); 
    var imagePathThumb = Path.Combine(Server.MapPath(Url.Content("~/Pictures/Upload/Thumbnail")), fileName); 

    imageFile.SaveAs(imagePathFull); 
    ThumbnailGenerator generator = new ThumbnailGenerator(); 
    generator.GetThumbnail(imagePathFull, imagePathThumb); 

    return new WrappedJsonResult 
    { 
     Data = new 
     { 
      IsValid = true, 
      Message = string.Empty, 
      ImagePath = Url.Content(String.Format("~/Pictures/Upload/Thumbnail/{0}", fileName)), 
      RealName = fileName 
     } 
    }; 
} 

最後的發送控制器,這裏是由所述第二形式被稱爲CON​​TROLER。

[HttpPost] 
public ActionResult Create(Recipe recipe) 
{ 
     if (ModelState.IsValid) 
     { 
      db.Recipes.Add(recipe); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(recipe); 
} 
+0

顯示你的一些代碼將幫助我們給你一些指導。 – Chris

+0

我編輯了我的文章! –

回答

2

你需要有圖像(或者,它看起來像,只是文件名)作爲你的食譜模型的一部分,並將其存儲在你的第二個形式在Html.HiddenFor元素。

然後,您將需要一個document.ready jQuery函數來查看fliename是否可用,並在有的情況下顯示它。可能這應該與您在上傳完成時調用的功能相同。

最後,當上傳在ajax方法中完成時,使用jQuery來更新帶有圖像文件名的隱藏字段,現在當您發回模型時,它具有顯示完整視圖所需的所有信息,包括圖片。

有意義嗎?

+0

我會在1或2天內嘗試這一點(現在非常忙於其他事情)。據我所知,這是有道理的,但如果你可以添加一些代碼或僞代碼給你的答案,它可以幫助我。 –

+0

非常感謝你!即使你沒有提供任何代碼,這正是我所需要的。你值得你的50分:) –

+0

哇謝謝。有點厲害,所以沒有得到它......但知道你可以做到! – KennyZ