Asp.net mvc MVC 4路由、Get/Post请求处理

Asp.net mvc MVC 4路由、Get/Post请求处理,asp.net-mvc,asp.net-mvc-4,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc 4,Asp.net Mvc Routing,我面临以下问题: 我有一个控制器,可以执行以下操作: [HttpGet] public ActionResult Index() { var viewModel = new IndexViewModel(); return View("Index", viewModel); } [HttpPost] public void ExportToExc

我面临以下问题:

我有一个控制器,可以执行以下操作:

        [HttpGet]
        public ActionResult Index()
        {
            var viewModel = new IndexViewModel();

            return View("Index", viewModel);
        }



        [HttpPost]
        public void ExportToExcell(LeadsViewModel model)
        {
            // Export to excell code goes here
        }
问题如下:

用户使用以下URL进入索引页面:/Controller/Index

然后用户将表单提交给Action ExportToExcel

数据被导出到Excel文件并下载,一切正常

URL变为/Controller/ExportToExcell

然后,当我单击Enter时,我将进入/Controller/ExportToExcell,但使用GET 当然,如果没有找到页面,问题是如何在MVC中正确处理这个问题。不要使用void作为post操作的返回类型,使用ActionResult

不要使用void作为post操作的返回类型,请使用ActionResult


我相信你的问题在于你没有返回FileResult,浏览器会将你重定向到你的帖子路径。现在无法测试它,但我相信下面的方法应该有效

[HttpPost]
public ActionResult ExportToExcell(LeadsViewModel model)
{
   // Generate the Excel file into a MemoryStream for example

   // Return a FileResult with the Excel mime type
   return File(fileStream, "application/vnd.ms-excel", "MyExcelFile.xls");
}
查看和以了解更多详细信息


请注意,我不完全确定这是否是Excel文件的mime类型,但如果您说您已经下载了该文件,您可能已经下载了:

我相信您的问题在于您没有返回文件结果,浏览器会将您重定向到您的发布路径。现在无法测试它,但我相信下面的方法应该有效

[HttpPost]
public ActionResult ExportToExcell(LeadsViewModel model)
{
   // Generate the Excel file into a MemoryStream for example

   // Return a FileResult with the Excel mime type
   return File(fileStream, "application/vnd.ms-excel", "MyExcelFile.xls");
}
查看和以了解更多详细信息


请注意,我不完全确定这是否是Excel文件的mime类型,但如果您说您已经下载了该文件,您可能已经下载了该文件:

您必须返回ActionResult,而不是void

 public ActionResult ExportToExcel(PagingParams args)
    {
        var data = new StudentDataContext().Student.Take(200).ToList();
        return data.GridExportToExcel<Student>("GridExcel.xlsx", ExcelVersion.Excel2007, args.ExportOption);
    }

请检查链接:

您必须返回ActionResult,而不是void

 public ActionResult ExportToExcel(PagingParams args)
    {
        var data = new StudentDataContext().Student.Take(200).ToList();
        return data.GridExportToExcel<Student>("GridExcel.xlsx", ExcelVersion.Excel2007, args.ExportOption);
    }

请检查链接:

您能分享您的ExportToExcell操作吗?这与你的问题无关。我想用这样的东西。我写了一个出口行动,但我的不起作用。如果你的有效,我可以用它。谢谢。这是我们团队开发的第三方dll的代码。它正在创建Excel可以读取的xml文件。您可以共享您的ExportToExcell操作吗?这与你的问题无关。我想用这样的东西。我写了一个出口行动,但我的不起作用。如果你的有效,我可以用它。谢谢。这是我们团队开发的第三方dll的代码。创建Excel可以读取的xml文件是返回ViewSomeView,viewModel也是不好的做法,因为事情会发生。。。我的意思是我有一个名为Foo{return ViewIndex,new ViewModel}的操作,我总是需要使用适合路由名称的return ViewModel,在其他情况下使用RedirectToAction@StringBuilder你应该在谷歌上搜索PRG后重定向获取模式,这很有趣而且。。。我对MVC应用程序的观点是一个相当好的主意。例如,查看返回ViewSomeView,viewModel也是一种不好的做法,因为事情会发生。。。我的意思是我有一个名为Foo{return ViewIndex,new ViewModel}的操作,我总是需要使用适合路由名称的return ViewModel,在其他情况下使用RedirectToAction@StringBuilder你应该在谷歌上搜索PRG后重定向获取模式,这很有趣而且。。。我对MVC应用程序的观点是一个相当好的主意。例如,见