分类:
2008-10-15 16:42:37
namespace Tip25 { public class SimpleViewEngine : IViewEngine { private string _viewsFolder = null; public SimpleViewEngine() { if (HttpContext.Current != null) { var root = HttpContext.Current.Request.PhysicalApplicationPath; _viewsFolder = Path.Combine(root, "Views"); } } public SimpleViewEngine(string viewsFolderPhysicalPath) { _viewsFolder = viewsFolderPhysicalPath; } public void RenderView(ViewContext viewContext) { if (_viewsFolder == null) throw new NullReferenceException("You must supply a viewsFolder path"); string fullPath = Path.Combine(_viewsFolder, viewContext.ViewName) + ".htm"; if (!File.Exists(fullPath)) throw new HttpException(404, "Page Not Found"); // Load file string rawContents = File.ReadAllText(fullPath); // Perform replacements string parsedContents = Parse(rawContents, viewContext.ViewData); // Write results to HttpContext viewContext.HttpContext.Response.Write(parsedContents); } public string Parse(string contents, ViewDataDictionary viewData) { return Regex.Replace(contents, @"\{(.+)\}", m => GetMatch(m, viewData)); } protected virtual string GetMatch(Match m, ViewDataDictionary viewData) { if (m.Success) { string key = m.Result("$1"); if (viewData.ContainsKey(key)) return viewData[key].ToString(); } return String.Empty; } } } |
namespace Tip25.Controllers { [HandleError] public class HomeController : Controller { public HomeController() { this.ViewEngine = new SimpleViewEngine(); } public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; ViewData["Message2"] = "Using a custom View Engine"; return View("Index"); } } } |
Here is the first message: {message} Here is the second message: {message2} |
Index view包含也以前后大括号为标记的标签。SimpleViewEngine.RenderView()方法用View Data中的项目来替换每个同名标签。当Index view被SimpleViewEngine呈现时,
[1]