현재 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);
}
일부 코드를 표시하면 도움이 될 것입니다. – Chris
내 게시물을 편집했습니다! –