StringBuilder
StringBuilder

Reputation: 1629

MVC 4 Routing , Get/Post requests handling

I'm faced with the following problem :

I have a controller with lets say the following actions:

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

            return View("Index", viewModel);
        }



        [HttpPost]
        public void ExportToExcell(LeadsViewModel model)
        {
            // Export to excell code goes here
        }

The problem is the following:

The User enters on Index page with this URL : /Controller/Index

Then the user submits the form to Action ExportToExcel

Data is exported to Excel( file downloaded ) and it's okay.

The URL becomes /Controller/ExportToExcell

Then when I am clicking "Enter" I am going To /Controller/ExportToExcell but with GET and of course falling with Page Not Found, the question is how properly to Deal with this in MVC

Upvotes: 1

Views: 1432

Answers (3)

RGR
RGR

Reputation: 1571

You must return ActionResult instead of void.

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

Please check the link: Export Action

Upvotes: 0

Jo&#227;o Sim&#245;es
Jo&#227;o Sim&#245;es

Reputation: 1361

I believe that your problem is that you aren't returning a FileResult, and the browser will redirect you to your post path. Can't test it right now, but I believe the following should work.

[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");
}

Check FileResult and Controller.File for more details.

As a note, I'm not completely sure if that's the mime type for an Excel file, but if you say you are already downloading the file, your probably already have it :)

Upvotes: 2

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

Don't use void as returned type of your post action, use an ActionResult

[HttpPost]
public ActionResult ExportToExcell(LeadsViewModel model)
{
   // Export to excell code goes here
   return RedirectToAction("Index");
}

Upvotes: 4

Related Questions