我是asp.net-mvc的新手,现在我正在处理返回excel文件以及错误消息,如果返回的文件缺少列,则用户单击该按钮。我使用return File()
返回我的文件进行查看,但我不知道如何一起发送错误消息。 (我试过ViewBag,但它没有工作)如何将文件发送回查看以及错误消息?
答案 0 :(得分:1)
我认为您可以尝试使用Ajax生成excel文件到服务器中的临时文件夹,并通过ajax响应下载,fronend代码如下所示:
$.blockUI({ message: '<h3><img src="@Url.Content("~/Content/images/busy.gif")" /> Please wait a moment...</h3>' });
$.ajax({
type: "POST",
url: '@Url.Action("ExportExcel","YourController")',
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
//console.log(data.result);
$.unblockUI();
if (data.fileName != "") {
window.location.href = "@Url.RouteUrl(new { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;
}
});
在控制器中:
[HttpPost]
public JsonResult ExportExcel()
{
DataTable dt = DataService.GetData();
var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
using (var exportData = new MemoryStream())
{
Utility.WriteDataTableToExcel(dt, ".xls", exportData);
FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
exportData.WriteTo(file);
file.Close();
}
var errorMessage = "you can return the errors in here!";
return Json(new { fileName = fileName, errorMessage = "" });
}
和下载动作
[HttpGet]
[DeleteFileAttribute]
public virtual ActionResult Download(string file)
{
string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
return File(fullPath, "application/vnd.ms-excel", file);
}
在这里,我创建了一个删除过滤器,用于在下载后自动删除文件:
/// <summary>
/// The Action filter for delete the file after downloaded
/// </summary>
public class DeleteFileAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Flush();
string filePath = (filterContext.Result as FilePathResult).FileName;
System.IO.File.Delete(filePath);
}
}
答案 1 :(得分:0)
我建议将文件作为模型返回,并将任何错误添加到控制器中的ModelState
,如下所示:
ModelState.AddModelError("Key", "Error Message");
如果您想将ModelState
解析为JSON以在javascript中使用,您可以使用此方法:
public static string ParseModelState(ModelStateDictionary modelState)
{
if (modelState == null) return "";
var dic = new Dictionary<string, string>();
for (var i = 0; i < modelState.Keys.Count; i++)
{
var firstOrDefault = modelState.Values.ElementAt(i).Errors.FirstOrDefault();
if (firstOrDefault != null)
dic.Add(modelState.Keys.ElementAt(i), firstOrDefault.ErrorMessage);
}
return System.Web.Helpers.Json.Encode(dic);
}
在你的观点中:
var modelState = @Html.Raw(Helpers.ParseModelState(ViewData.ModelState));
答案 2 :(得分:0)
是服务器上的文件存储区吗?如果是,您可以将URL作为JSON的标准返回到文件中,并且在JavaScript中您可以显示错误并在新窗口中加载文件
return return Json(new {error="Error Message", fileurl="http://yoursite.com/file.etx"});
在客户端(我猜你要发布信息)
$.ajax({
type: "POST",
url: '@Url.Action("Action", "Control")',
data: { para: "value" },
dataType: "json",
success: function(data) {
$('#errorlabel').html(data.error);
window.open(data.fileurl,_blank);
},
error: errorFunc
});
希望这能让你有个好主意开始