Reputation: 12441
Hi I'm trying to return a view that is xml, meaning the content type will be "text/xml", and the view is using ASP.NET MVC razor. Another post ASP.NET MVC and text/xml content type showed how to do it with aspx view. How do I get the same done with razor?
Upvotes: 12
Views: 19638
Reputation: 131
A couple things you need to be aware of.
Controller
[HttpGet]
public ViewResult SomeXML()
{
return View();
}
View (SomeXML.cshtml)
@{
Layout = null;
Response.ContentType = "text/xml";
}<?xml version="1.0" encoding="utf-8" ?>
<element>
...
</element>
Upvotes: 1
Reputation: 4488
For anyone trying to do this is ASP.NET Core, you can find the Response as a property of the Context:
@{
Context.Response.ContentType = "text/xml";
}
<?xml version="1.0" encoding="UTF-8" ?>
<doc>
...
</doc>
Although I found setting the content type in the Action worked perfectly well (as suggested by @Luis above)
Upvotes: 3
Reputation: 28120
If you prefer you can instead make the content type change from your view action, like so:
public ActionResult MyAction() {
Response.ContentType = "text/xml";
return View();
}
Upvotes: 8
Reputation: 8372
I found an example of an rss feed produced with a razor view here:
Basically you have to set the Response.ContentType
to "text/xml"
, and then you can just write your xml as if it was html.
You have to scroll down to see the actual code so I'll copy it here:
@{
var db = Database.OpenFile("Database.sdf");
var getRss = db.Query("SELECT TOP(5) * FROM Table" );
Response.ContentType = "text/xml";
}
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>Website name</title>
<link>website link</link>
<description>News for website</description>
<dc:language>en-gb</dc:language>
<dc:creator>email</dc:creator>
<dc:rights>Copyright 2010</dc:rights>
<admin:generatorAgent rdf:resource="http://www.styledna.net/" />
@foreach (var row in getRss) {
<item>
<title>@row.title</title>
<link>@row.link</link>
<description> some html desc for the item </description>
</item>
}
</channel>
</rss>
Upvotes: 34