Asp.Net MVC 学习心得 之 View

简介:

一、使用View Data

首先要在Controller里加代码:

    public class ProductController : Controller
    {
        //
        // GET: /Product/

        public ActionResult Index()
        {
            ViewData["Message"] = "Hello World";
            return View();
        }

    }

然后在View里添加代码:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ToyStore.Models.Products>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Index</h2>
    <%=ViewData["Message"] %>
</asp:Content>

内容就被传递了,但这样由于传入的值可能是任何类型的,所以你要自己做类型转换了,哈哈。

ViewData.Model是可以让你有个强类型的

ViewData.Model = _dataModel.ProductSet.ToList(); 

 

二、预防javascript注入攻击

默认是预防的,如果不想使用看下面的代码:

[ValidateInput(false)]  
[AcceptVerbs(HttpVerbs.Post)]  
public ActionResult Create([Bind(Exclude="Id")]Product productToCreate)  
{  
    if (!ModelState.IsValid)  
        return View();  
  
    try  
    {  
        _dataModel.AddToProductSet(productToCreate);  
        _dataModel.SaveChanges();  
  
        return RedirectToAction("Index");  
    }  
    catch  
    {  
        return View();  
    }  
} 

主要是那个[ValidateInput(false)]

三、可替换的View Engine

Asp.net Mvc里的View Engine是可以替换的,默认的engine是叫做Web Forms View Engine.现在已经有几个开源的View Engine了

http://www.codeplex.com/MVCContrib 可以到这里找找看,一个网站可以同时使用几个View Engine,可以在Global.asax里配置,使用不同的扩展名来区分使用不同View Engine 比如:.aspx页面就使用Web Forms View Engine.

我们也可以自定义一个View Engine,从VirtualPathProviderViewEngine 继承出一个类就可以了。

using System.Web.Mvc;  
  
namespace MvcApplication1.MyViewEngines  
{  
    public class SimpleViewEngine : VirtualPathProviderViewEngine  
    {  
        public SimpleViewEngine()  
        {  
            this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.simple", "~/Views/Shared/{0}.simple"};  
            this.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.simple", "~/Views/Shared/{0}.simple" };  
        }  
  
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)  
        {  
            var physicalPath = controllerContext.HttpContext.Server.MapPath(viewPath);  
            return new SimpleView(physicalPath);  
        }  
  
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)  
        {  
            var physicalPath = controllerContext.HttpContext.Server.MapPath(partialPath);  
            return new SimpleView(physicalPath);  
        }  
    }  
} 
 
在Global.asax里这样写
protected void Application_Start()  
{  
    RegisterRoutes(RouteTable.Routes);  
  
    ViewEngines.Engines.Add(new SimpleViewEngine());  
} 

然后自己写一个view的页面类:

namespace MvcApplication1.MyViewEngines  
{  
    public class SimpleView : IView  
    {  
        private string _viewPhysicalPath;  
  
        public SimpleView(string viewPhysicalPath)  
        {  
            _viewPhysicalPath = viewPhysicalPath;  
        }  
         
        #region IView Members  
  
        public void Render(ViewContext viewContext, TextWriter writer)  
        {  
            // Load file  
            string rawContents = File.ReadAllText(_viewPhysicalPath);  
  
            // Perform replacements  
            string parsedContents = Parse(rawContents, viewContext.ViewData);  
  
            // Write results to HttpContext  
            writer.Write(parsedContents);  
        }  
 
        #endregion  
  
        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;  
        }  
      
    }  
}

定义一个Controller:

using System.Web.Mvc;  
  
namespace MvcApplication1.Controllers  
{  
    public class SimpleController : Controller  
    {  
        public ActionResult Index()  
        {  
            ViewData["message"] = "Hello World!";  
            return View();  
        }  
    }  
}

而页面可以写成:Views\Simple\Index.simple

 

<html>  
  
<head><title>Index Simple View</title></head>  
  
<body>  
  
<h1>{message}</h1>  
  
</body>  
  
</html>  

主要看{message}被解析出来了

 

注:上面的代码是从别人书里炒来的,不好意思

在View里有个HtmlHelper的东西 以后再写。

路漫漫其修远兮 吾将上下而求索



本文转自 lu xu 博客园博客,原文链接: http://www.cnblogs.com/dotLive/archive/2009/03/09/1407073.html  ,如需转载请自行联系原作者

相关文章
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
42 0
|
1月前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
29 0
|
1月前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
5 0
|
1月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
100 5
|
3月前
|
XML 前端开发 应用服务中间件
Cannot resolve MVC View解决方案
Cannot resolve MVC View解决方案
124 0
Cannot resolve MVC View解决方案
|
3月前
|
XML 前端开发 定位技术
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
25 0
|
3月前
|
前端开发
.net core mvc获取IP地址和IP所在地(其实是百度的)
.net core mvc获取IP地址和IP所在地(其实是百度的)
124 0
|
3月前
|
前端开发 JavaScript Java
springboot 出现 Cannot resolve MVC View ‘index‘ 问题解决办法,前后端不分离项目前端文件存放位置,已经如何访问
springboot 出现 Cannot resolve MVC View ‘index‘ 问题解决办法,前后端不分离项目前端文件存放位置,已经如何访问
108 0
|
5月前
|
开发框架 自然语言处理 前端开发
基于ASP.NET MVC开发的、开源的个人博客系统
基于ASP.NET MVC开发的、开源的个人博客系统
52 0
|
8月前
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
117 0