简体   繁体   中英

Calling a Web API Controller from an MVC View to return an XML file

I have a single project that is both a Web API and MVC project. I have an MVC View that displays the results of an MVC controller query; I also expose the same data from the Web API controller.

My goal is to put a link on the View that will call the Web API and return the XML response as a file, passing in the same query that was used to generate the view.

What's a good way to implement this? For bonus points, can I parse the Web Api Route Name in my View to build the link?

EDIT

I have tried Slicksim's suggestion:

<a href="@Url.HttpRouteUrl("NameOfWebApiRoute", new { id = Model.Id })">
  Testing 123
</a>

and that just displays the XML result in the browser window. My goal is to transfer this as an XML file, eg to show the Save As dialog and send it.

You can build a link as you would do with Url.RouteUrl, the url helper has a HttpRouteUrl.

That should build you a simple href that you can use to browse off to the web api route and get the xml file, the browser can then decide how to handle it.

http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.httprouteurl(v=vs.118).aspx

Try adding the html5 "download" attribute as suggested here: Force a browser to save file as after clicking link

<a href="@Url.HttpRouteUrl("NameOfWebApiRoute", new { id = Model.Id })" download>
  Testing 123
</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM