Reputation: 21
I need to show some text and image data (which are in html markup) into a Razor view from a XML file. for example I have the following Xml:
<newsitems>
<news id="1">
<body>
<p>lorem ipsum <h2>dolor</h2>.</p>
</body>
</news>
</newsitems>
then I need to show that inner html into a view. please show me the best way and code if possible! thx.
Upvotes: 0
Views: 1607
Reputation: 42497
Create a view model (which is just a fancy name for a class used to represent data in a well-understood, structured way) in the Models
directory of your MVC application, if you have one, such as:
public class NewsItemViewModel
{
public int Id { get; set; }
public string Body { get; set; }
}
Create an action in your controller to extract instances of NewsItemViewModel
from the XML. I'd use LINQ-to-XML. Let's assume you have a controller named NewsController
in your Controllers
directory.
public class NewsController : Controller
{
public ActionResult Index()
{
// replace XElement.Parse(...) below to your own routine to load the XML file
var newsItems = (from news in XElement.Parse(@"<newsitems>
<news id=""1"">
<body>
<p>lorem ipsum <h2>dolor</h2>.</p>
</body>
</news>
</newsitems>").Descendants("news")
let body = news.Descendants("body").First()
select new NewsItemViewModel {Id = (int)news.Attribute("id"), Body = body.Value });
return View(newsItems);
}
}
Now create a view for NewsController.Index
(following my example, that'd be Views/News/Index.cshtml
).
@model IEnumerable<YourApplicationNameSpace.Models.NewsItemViewModel>
@foreach(var newsItem in Model)
{
<div class="newsitem">
@Html.Raw(newsItem.Body)
</div>
}
A couple of notes:
NewsItemViewModel.Body
property to strip potentially dangerous HTML or script to prevent malicious content from breaking your site or worse.body
node of each news
element in your XML in CDATA
so that the HTML content does not break your XML file and thus the ability to successfully parse it.Upvotes: 3