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}被解析出来了

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值