ASP.NET MVC Razor语法及实例

时间:2022-08-26 20:49:31

1.混合HTML与Razor脚本

知识点:(1).cshtml怎样引用访问数据, (2).if  for 与html嵌套

@using System.Data
@using CIIC.TCP.Entity;
@{
List
<taut_MenuEntity> MenuList = (List<taut_MenuEntity>)Session["NavigateMenu"];
}
<nav class="navbar-default navbar-static-side" role="navigation">
<div class="sidebar-collapse">
<ul class="nav" id="side-menu">
<li class="nav-header">
<div class="dropdown profile-element">
@Html.ActionLink("Xxx平台", "..\\Login\\FirstPage", new { id = "", loginUserId = ViewBag.loginUserId as string }, new { style = "font-size:large;font-weight:bold" })
</div>
<div class="logo-element">
IN+
</div>
</li>
<!--权限菜单开始-->
@if (MenuList != null)
{
foreach (taut_MenuEntity item in MenuList)
{
if (item.Level == 1)
{
<li class="">
<a href="@item.Url">
<i class="fa fa-th-large"></i><span class="nav-label" data-i18n="nav.dashboard">@item.ModuleName</span><span class="fa arrow"></span>
</a>
<ul class="nav nav-second-level collapse">
@{
List
<taut_MenuEntity> SubMenuList = MenuList.FindAll(t => t.ModuleName == item.MenuName && t.Level.Value==2 ).OrderBy(t=>t.OrderId).ToList();
foreach (var subItem in SubMenuList)
{
<li class=""><a href="@subItem.Url">@subItem.MenuName</a></li>
}
}
</ul>
</li>
}
}
}
<!--权限菜单结束-->
</ul>
</div>
</nav>

2.布局相关方法 @RenderSection

部分一:在_Layout.cshtml 中定义待插入的"子模块"占位符

<script type="text/javascript">
@RenderSection(
"HeadScript", false)
</script>

部分二:在Xxx.cshtml中定义对应的填充块

@section HeadScript{
function del_comfire()
{
if(confirm("确定删除?"))
{
return true;
}
else{
this;
}
}
}

3.模板中的常用方法

@{
ViewBag.Xxx;
}
@Url.Content("Xxx")"  //仅仅生成链接文本
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>

4.Html助手方法

@Html.ActionLink("Create New", "Create")
<li>@{Html.RenderAction("CartSummary", "ShoppingCart");}</li>  //参考PartialViewResult
@{Html.RenderPartial(“SomePartial”);//注意有大括号

参考

@{
string message = “
<strong>This is bold!</strong>”;
}
<span>@Html.Raw(message)</span>

 

5.PartialViewResult技术

在模板中调用其它Controller和Action,将其返回结果填充模板,参考Html.RenderAction()方法

6.模板中的小括号语法

如果直接写@rootName.Models将会有编译错误 

//视图cshtml中的实验代码和语法现象
@{
string rootName="MyApp";
}
<span>@(rootName).Models</span>

 

7.Razor的原生Href方法

8.Switch条件判断例子

9.Razor的模板的注释语法以及模板字面值直接输出

10.HTML编码即@HTML.Raw()方法

11.JavaScript编码即@Ajax.JavaScriptEncode()方法