- @{
- ViewBag.Title = "首页";
- //
- // some code
- //
- }
- @section SectionA{
- <div>这里是SectionA:也不需要写神马runat="server"啊,有木有</div>
- }
- @section SectionB{
- <div>这里是SectionB:也不需要写神马<asp:Content />啊,有木有</div>
- }
- <div>
- 这里就是渲染Body啦.~~不需要写神马<asp:Content />,其实因为RenderBody()不在有歧义.
- </div>
最后显示的页面效果:
498)this.width=498;'' onmousewheel = ''javascript:return big(this)'' title="image" border="0" alt="image" src="/uploadfile/201301/6/1A184942495.png" />
498)this.width=498;'' onmousewheel = ''javascript:return big(this)'' title="image" border="0" alt="image" src="/uploadfile/201301/6/1A184942116.png" />
问:为什么为什么要推荐方式1呢?
答:因为RenderSection()方法有2个重载.
如果使用第一个只接受一个string类型参数的重载的话.~如果你在具体的View中没有利用@section来定义实现的话,运行会报错.所以需要配合另外一个方法IsSectionDefined()来使用,才能防止报错.
而使用第2个重载就可以利用第二个bool类型的参数指明该Section是否为必须的.所以可以在使用该RenderSection方法的时候直接利用第二个重载,再把bool参数值设为false,即使你在具体的View中没有声明实现@section,运行起来也一如既往地蛋定,不Show黄页.
在这里只是做个一简单的示范,新建一个类文件,替换如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data;
- using System.Data.SqlClient; //在这里就用ADO.NET方式吧.EF我接触不久!
- namespace Mvc3Application1
- {
- public class ReaderSQL_Date
- {
- private static readonly string _SQL_CONN_STR = "server=.\\mssqlserver,1433;uid=sa;pwd=yourpwd;database=student;";
- public static IList<StudentEntity> GetAllStudent()
- {
- //这里仅仅是做演示,生产环境并不这样写
- using (SqlConnection conn = new SqlConnection(_SQL_CONN_STR))
- {
- SqlCommand cmd = conn.CreateCommand();
- cmd.CommandType = CommandType.Text;
- cmd.CommandText = "SELECT [Sno],[Sname],[Sage] FROM [dbo].[STUDENT]";
- IList<StudentEntity> result = new List<StudentEntity>();
- conn.Open();
- using (SqlDataReader sdr = cmd.ExecuteReader())
- {
- while (sdr.Read())
- {
- result.Add(new StudentEntity
- {
- S_No = sdr.GetInt32(0),
- S_Name = sdr.GetString(1),
- S_Age = sdr.GetInt32(2)
- });
- }
- }
- //SqlConnection.ClearPool(conn); //可选清理连接池.
- return result;
- }
- }
- }
- public class StudentEntity
- {
- public int S_No { get; set; }
- public string S_Name { get; set; }
- public int S_Age { get; set; }
- }
- }
_