MVC3 Export to File Design
I have a strongly typed View that displays a Model using ASP.NET MVC3. I want to add a link so the user can download the model displayed in the view into a CSV file. I was thinking the link would point to another action on the controller that took the model as an argument.
What's the best practice?
- Should I be using jQuery .post, Html.ActionLink, etc.?
- How do I pass the model that is displayed on the view back to the controller? I read something that made me think you can't pass the model back to the controller. I guess an alternative would be to get the data that hydrated the model from the database again, but that means a round trip to the database.
- An alternative to p开发者_运维问答assing the model back to the controller is to pass the div element back to the controller. This may not get exactly what I want (and seems hacky).
Thanks for your input!
You could store the model as json on the client, then post back and convert to csv from there.
You should create an action method that returns a custom ViewResult
for your CSV file. That method could accept the same parameter used to return the model for the display action method and use it to retrieve the model (from a repository, for example) and return a file result.
To implement that functionality, you would have to create a custom CsvFileResult
class deriving from System.Web.Mvc.FileResult
(that itself derives from System.Web.Mvc.ActionResult
). The constructor of that class should take your model, create the comma separated output and return a file result with the MIME type text/csv.
As an example, your Controller could look like this:
public class ModelController : Controller
{
private readonly IModelRepository _modelRepository;
public DemoController(IModelRepository modelRepository)
{
_modelRepository = modelRepository;
}
public ActionResult Display(int id)
{
var model = _modelRepository.Retrieve(id);
return View(model);
}
public FileResult ExportCsvFile(int id)
{
var model = _modelRepository.Retrieve(id);
return new CsvFileResult(model);
}
}
On the client, you could output a link to the ExportCsvFile
action method using the ActionLink
helper method and the overload accepting parameter values:
@Html.Helper("ExportCsvFile", "Model", new { id = Model.ModelID })
精彩评论