I have a simple project where the start page shows a list of books. How to make the same page, but with display as XML?
Controller method:
public IActionResult Index()
{
// stored procedure
var books = _context.Bookstable.FromSqlRaw("SelectAll").ToList();
return View(books);
}
View
@model IEnumerable<MyProject.Models.Book>;
@{
ViewData["Title"] = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="@Url.Content("~/css/style.css")" rel="stylesheet" type="text/css" />
<div>
<Table>
<tr>
<th><h5>Author</h5></th>
<th><h5>Name</h5></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Author</td>
<td>
<a href="@Url.Action("BookPage", "Home", new {id = @item.Id })">@item.Name</a>
</td>
</tr>
}
</Table>
<br/><br/><br/>
</div>
I need to return serialized data from the controller as XML, the Razor view accepts data and displays it.
There are many questions on this topic, but I did not find an answer to mine.
It should be something like this controller method:
public IActionResult IndexXML()
{
var books = _context.Bookstable.FromSqlRaw("SelectAll").ToList();
// how to convert 'books' to XML?
booksXML =
return View(booksXML, "text/xml");
}
Should I create a new table (in SQL Server) with a different (XML) data type?
Do I need to rewrite the stored procedures (it would be nice to keep the old ones, but convert the data after retrieving it)?
I'm probably missing something else.
View
@* @model IEnumerable<MyProject.Models.Book>; need XMLstring *@
{ *@
Context.Response.ContentType = "text/xml";
} *@
<?xml version="1.0" encoding="UTF-8" ?>
{
ViewData["Title"] = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="@Url.Content("~/css/style.css")" rel="stylesheet" type="text/css" />
<div>
<h3>XML</h3>
<br/><br/>
<Table>
<tr>
<th><h5>Author</h5></th>
<th><h5>Name</h5></th>
</tr>
@foreach (@* ??????? *@)
{
<tr>
@* ??????? *@
</tr>
}
</Table>
<br /><br /><br />
</div>