https://uchukamen.wordpress.com/2011/01/30/asp-net-mvc2-%e3%81%a7-linq-to-xml/
で、ASP.NET MVC2 で LINQ to XML をしてみたが、今回はMVC3 Razor で LINQ to XMLしてみる。
1. MVC3 の新規プロジェクトを作成。ビューエンジンは Razor
2. YahooRssModel.cs をモデルに追加、次のコードを実装。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication7.Models
{
public class YahooRssModel
{
public string title { get; set; }
public string link { get; set; }
public string pubDate { get; set; }
public string guid { get; set; }
}
}
3. YahooRssController を追加し、次のコードを実装。
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;
using MvcApplication7.Models;
namespace MvcApplication7.Controllers
{
public class YahooRssController : Controller
{
//
// GET: /YahooRss/
public ActionResult Index()
{
var res = new List<YahooRssModel>();
ViewData[“Message”] = “ASP.NET MVC へようこそ”;
string yahooRssUrl = “http://dailynews.yahoo.co.jp/fc/rss.xm”;
XDocument rss = XDocument.Load(yahooRssUrl);
res = (from item in rss.Descendants(“item”)
select new YahooRssModel
{
title = (item.Element(“title”).Value ?? “”),
link = item.Element(“link”).Value,
pubDate = item.Element(“pubDate”).Value,
guid = item.Element(“guid”).Value
}).ToList();
return View(res);
}
}
}
4. ビューを追加。
Views にYahooRss フォルダーを作成し、その中にビューを追加する。そのとき、ビュー名は、Index。ビューエンジンは Razor(CSHTML)、「厳密に型指定されたビューを作成する」にチェック。モデルクラスのドロップダウンリストより、モデルクラスに追加した YahooRssModel を追加。スキャフォールディング・ビュー・テンプレートは、List を選択。
http://…/YahooRss/ をリストすると次のような一覧表示が作成される。もとはLINQデータなので、Create, Edit, Delete は対応できないので、次のコードを削除する。
<p>
@Html.ActionLink(“Create New”, “Create”)
</p>
<th></th>
<td>
@Html.ActionLink(“Edit”, “Edit”, new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink(“Details”, “Details”, new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink(“Delete”, “Delete”, new { /* id=item.PrimaryKey */ })
</td>
以上で、次の簡単なリスト表示ができる。
コメントを残す