2012-09-16 8 views
1

현재 MVC3에 첫 번째 응용 프로그램을 구축 중입니다. 내 견해 중 하나에는 2 가지 형태가 있습니다. 하나는 이미지를 선택하고 AJAX (다른 컨트롤러를 호출하고 post과 같은 숨겨진 IFrame을 사용)를 사용하여 페이지에서 이미지를 표시/업로드하는 것입니다. 다른 양식은 이름, 주소 등의 정보를 입력하는 것입니다. 또한 첫 번째 양식을 사용하여 이미지를 선택하고 가져 오면 숨겨진 필드가 두 번째 양식에 채워 지므로 Create 컨트롤이 호출 될 때 모든 것이 만들어집니다 데이터베이스에.MVC3의 두 가지 양식이 원치 않는 새로 고침을 유발합니다.

이 모든 것은 완벽하게 작동하지만 사용자가 실수로 두 번째 양식의 숫자 입력란에 텍스트를 입력하면 모델 유효성 검사가 필요하며 오류가 빨간색으로 표시되는 포스트 백이 있습니다. 이렇게하면 첫 번째 형식은 모든 정보를 잃어 버리고 파일 입력 컨트롤로 재설정되고 이미지는 표시되지 않습니다.

누구든지이 문제를 해결하는 방법을 알고 있습니까? 나는 MVC3와 AJAX에 대해 매우 익숙하다. 그래서 나는 잘못된 것을하고있다.

최종 목표는 일단 그림이 페이지에 표시되고 업로드되면 두 번째 양식의 유효성이 확인되고 내 Create 컨트롤로 보낼 때까지 그대로 유지됩니다.

감사합니다.

편집 : 일부 사람들은 코드를 요청합니다. 여기 있습니다! 이것은이다 : 여기서

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

마지막으로 전송하기위한 제어이며, 여기에서 두 번째 형태에 의해 호출 CONTROLER이다.

[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 요소에 두 번째 형태로 저장합니다.

다음은 fliename이 있는지 확인하기 위해 document.ready jQuery 함수가 필요할 경우 표시하고 있으면 표시합니다. 이는 업로드가 완료 될 때 호출하는 것과 동일한 함수를 호출해야합니다.

마지막으로 ajax 메서드로 업로드가 완료되면 jQuery를 사용하여 숨겨진 필드를 이미지 파일 이름으로 업데이트하십시오. 이제 모델을 포스트 백하면 그림을 포함하여 전체보기를 표시하는 데 필요한 모든 정보가 포함됩니다 .

의미가 있습니까?

+0

1 일 또는 2 일 후에 이것을 시도 할 것입니다. 제가 말할 수있는 한, 이것은 합리적입니다. 그러나 당신이 당신의 대답에 약간의 코드 또는 의사 코드를 추가 할 수 있다면 그것은 저에게 도움이 될 것입니다. –

+0

정말 고마워요 !!! 비록 당신이 어떤 코드도 제공하지 않았더라도, 이것은 내가 필요한 것입니다. 너는 너의 50 점을 가치가있다 :) –

+0

와우 감사. Kinda는 지금 당황 했어. 그래서 그것에 가지 않았다. .. 그러나 당신이 그것을 할 수 있었다라는 것을 알고 있었다! – KennyZ

관련 문제