【发布时间】:2014-09-11 23:22:29
【问题描述】:
我目前正在实习,据我所知,MVC 中的控制器应该只用于流量,并且只能用于流量。我还被告知称为“服务层”的东西,这听起来像是我应该为控制器执行任何数据/业务逻辑的地方。
我一直在四处寻找这方面的示例和教程,但我没有找到任何对我来说足够愚蠢的东西,因为我大约一个月前才学习了 MVC。我想知道是否有人能够解释并向我展示如何将以下ActionResult Index 业务逻辑转移到“服务层”中。
public class LakerLegendsController : Controller
{
string pathway1 = HostingEnvironment.MapPath(@"~/App_Data/Announcement1.txt");
string pathway2 = HostingEnvironment.MapPath(@"~/App_Data/Announcement2.txt");
string pathway3 = HostingEnvironment.MapPath(@"~/App_Data/Announcement3.txt");
private MoviesEntities db = new MoviesEntities();
public ActionResult Index()
{
// Setting some ViewBag texts from announcement files.
string text1 = System.IO.File.ReadAllText(pathway1);
ViewBag.TextHTML1 = text1;
string text2 = System.IO.File.ReadAllText(pathway2);
ViewBag.TextHTML2 = text2;
string text3 = System.IO.File.ReadAllText(pathway3);
ViewBag.TextHTML3 = text3;
// Following pulls some XML information
XDocument xmlFile = XDocument.Load(@"http://na.leagueoflegends.com/en/rss.xml");
var LoLtitles = from service in xmlFile.Descendants("item")
select (string)service.Element("title");
var LoLlinks = from service in xmlFile.Descendants("item")
select (string)service.Element("link");
var LoLdescriptions = from service in xmlFile.Descendants("item")
select (string)service.Element("description");
var LoLDates = from service in xmlFile.Descendants("item")
select (string)service.Element("pubDate");
var servicing = LoLdescriptions.ToArray();
for (int i = 0; i < 4; i++)
{
servicing[i] = Regex.Replace(Server.HtmlDecode(servicing[i]), @"<[^>]*>", String.Empty);
}
ViewBag.titles = LoLtitles.ToArray();
ViewBag.links = LoLlinks.ToArray();
ViewBag.descriptions = servicing;
ViewBag.dates = LoLDates.ToArray();
// Pulls the DB Table
var users = db.Users.Include(u => u.championList).Include(u => u.championList1).Include(u => u.championList2).Include(u => u.eloList).Include(u => u.rankList).Include(u => u.roleList).Include(u => u.roleList1);
return View(users.ToList());
}
}
这段代码所做的只是返回一个数据库表,以及一些提取 XML 文件并解析其中一些信息的额外逻辑。
我想知道如何将这个特定示例转换为使用服务层(或者我应该用于逻辑的任何东西)。请尽量简化,因为我还是 MVC 的新手。
【问题讨论】:
标签: asp.net-mvc model-view-controller asp.net-mvc-5 service-layer