0

我正在使用 html.beginform 上传文件;在验证文件时如果有错误如何向用户显示消息以免丢失布局样式?

视图中的代码:

<div id="result">
    @Html.ValidationSummary(true)
</div>
@using (Html.BeginForm("Submit", "BulkUpload",
                         FormMethod.Post, new { id = "uploadForm", enctype = "multipart/form-data" }))
{ 
    @(Html.Telerik().Upload()
            .Name("UploadAttachment")
            .Multiple(false)                 
    )
    <input type="submit" id="btnSaveOnDatabase" value="Submit" class="t-button" />
}

控制器中的代码:

{
    ...
    var fileName = Path.GetFileName(file.FileName);
    var extension = Path.GetExtension(file.FileName);
    if (!xlExtensions.Any(item => item == extension))
    {
        ModelState.AddModelError("", "not .xls file");
        break;
    }
    return PartialView("~/Views/BulkUpload.cshtml",uploadDT);

}

验证摘要显示但刷新整个页面;我失去了指定的布局。任何处理这个好消息的建议.. :)

4

1 回答 1

0

调整了这个...... :).. 它对我有用......

http://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3.aspx

public class WrappedJsonResult : JsonResult     
{         
   public override void ExecuteResult(ControllerContext context
     {
         context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");            
         base.ExecuteResult(context); 
         context.HttpContext.Response.Write"</textarea></body></html>");  
         context.HttpContext.Response.ContentType = "text/html";       
     }    
} 

控制器代码:

 if (cond.)
 {
     return new WrappedJsonResult   
     { 
            Data = new { IsValid = false,
                         Message = <error message>,
                         ImagePath =string.Empty
                       }
     }; 
} 

在 HTML 中:

<iframe id="UploadTarget" name="UploadTarget" onload="Upload_Complete();" style="position: absolute; left: -999em; top: -999em;"></iframe> <div id="Images"></div> 

查询:

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;  
   //Hide the image before adding to the DOM 
   $(img).hide();
   imgDiv.appendChild(img);
   //Now fade the image in
   $(img).fadeIn(500, null);
  } 
于 2013-08-14T14:12:06.857 回答