MVC5使用jQueryAjax验证模型并下载文件
我有MVC控制器动作,它以一些模型作为参数。如果模型无效,则返回JSON,否则返回文件MVC5使用jQueryAjax验证模型并下载文件,jquery,ajax,asp.net-mvc,download,jquery-ajaxq,Jquery,Ajax,Asp.net Mvc,Download,Jquery Ajaxq,我有MVC控制器动作,它以一些模型作为参数。如果模型无效,则返回JSON,否则返回文件 public class MainModel { public DownloadModel Downlaod {get;set;} } [ValidateAjaxRequest] public ActionResult DownloadFile(DownloadVM model) { // get file using model return File(byte[],"contenttype
public class MainModel
{
public DownloadModel Downlaod {get;set;}
}
[ValidateAjaxRequest]
public ActionResult DownloadFile(DownloadVM model)
{
// get file using model
return File(byte[],"contenttype")
}
注意,ValidateAjaxRequest
是actionfilteratribute
,它检查是否是ajax请求,如果是,则使用Json返回所有错误
public class ValidateAjaxRequestAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errors = new List<MyStatus>();
//loop through all errors here and build errors list
filterContext.Result = new JsonResult()
{
Data = errors
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}
我之所以使用ajaxpost而不是典型的表单post,是因为我在同一个视图上有一些我不想发布的其他控件,而且如果ModelState无效,我也不想刷新整个视图。
像下面这样的事情我不想做
public ActionResult DownloadFile(MainModel model)
{
if(ModelState.IsValid)
{
// get file using model.Download
return File(byte[],"contenttype")
}
return View("Index",model)
// here i have to post entire MainModel and also re-render
// entire View if ModelState is not valid.
// i do not like this approach so im using ajax to post only
// what i needed and without needing to re-render view
}
不能使用ajax方法返回文件。但是,您可以返回文件路径的url,以允许用户下载它-请参阅examples@StephenMuecke我在前面看到了这篇文章,但为了让它起作用,我必须先将文件存储在服务器上。然后我还需要一些工作来删除该文件。相反,我试图在内存中创建文件,并将其作为blob返回。但是,您可以返回文件路径的url,以允许用户下载它-请参阅examples@StephenMuecke我在前面看到了这篇文章,但为了让它起作用,我必须先将文件存储在服务器上。然后我还需要一些工作来删除该文件。相反,我试图在内存中创建文件并将其作为blob返回。
public ActionResult DownloadFile(MainModel model)
{
if(ModelState.IsValid)
{
// get file using model.Download
return File(byte[],"contenttype")
}
return View("Index",model)
// here i have to post entire MainModel and also re-render
// entire View if ModelState is not valid.
// i do not like this approach so im using ajax to post only
// what i needed and without needing to re-render view
}