MVC客户端使用 Mustache.js把json数据填充到模版中
使用Mustache的好处是:可以把一些反复用到的html部分定义成Mustache模版,以便多次使用。使用Mustache的大致步骤是:
→从后台拿到json数据
→获取前台页面预先定义好Mustache模版(占位符必须和从后台传来的的字段或属性名一致)
→遍历每行的json数据,使用Mustache.render(template, row)方法把json数据填充到对应的占位符,得到html内容
→把html内容追加到页面的某个位置
显示一个足球俱乐部的下拉框:
当点击下拉框,显示该俱乐部的球员:
创建一个ClubModel.edmx模型,Team和Player是1对多关系:
把模型中的数据更新到数据库,并在数据库中添加一些数据:
创建与Team对应的ViewModel为TeamVm。
using System.Web.Mvc;
namespace MvcApplication1.Models.ViewModels
{
public class TeamVm
{
public TeamVm()
{
Players = new List<SelectListItem>();
}
[Display(Name = "俱乐部")]
public int ID { get; set; }
public string Name { get; set; }
public IEnumerable<SelectListItem> Players { get; set; }
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
创建与Plyer对应的ViewModel为PlayerVm。
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models.ViewModels
{
public class PlayerVm
{
[Display(Name = "球员")]
public string Name { get; set; }
[Display(Name = "位置")]
public string Position { get; set; }
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
HomeController部分2个控制器方法,一个显示下拉框,一个响应下拉框的change事件。
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcApplication1.Models;
using MvcApplication1.Models.ViewModels;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
//把Team显示到下拉框中
public ActionResult Index()
{
var teamVm = new TeamVm();
using (var context = new ClubModelContainer())
{
var teams = context.Team.ToList();
teamVm.Players = teams.Select(t => new SelectListItem()
{
Text = t.Name,
Value = t.ID.ToString()
});
}
return View(teamVm);
}
//响应下拉框
public JsonResult PlayersByTeamID(int id)
{
IEnumerable<PlayerVm> playersVmList = new List<PlayerVm>();
using (var context = new ClubModelContainer())
{
var players = context.Player.Where(x => x.TeamID == id).ToList();
playersVmList = players.Select(p => new PlayerVm()
{
Name = p.Name,
Position = p.Position
});
}
return Json(playersVmList, JsonRequestBehavior.AllowGet);
}
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Home/Index.cshtml视图部分:
● 定义Mustache模版,占位符与json数据一致。
● 下拉框触发change事件,获取后台返回的json数据,填充到Mustache模版模版,并把html内容追加到页面。
@model MvcApplication1.Models.ViewModels.TeamVm
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
@Html.LabelFor(model => model.ID)
@Html.DropDownListFor(model => model.ID, Model.Players)
</div>
<div id="playersDiv">
</div>
@section scripts
{
<script src="~/Scripts/mustache.js"></script>
<script type="text/javascript">
$(function() {
$('#ID').change(function() {
var id = $('#ID').val();
var playersDiv = $('#playersDiv');
$.ajax({
cache: false,
type: "GET",
url: "@Url.Action("PlayersByTeamID","Home")",
data: { "id": id },
success: function (data) {
var result = "";
playersDiv.html('');
$.each(data, function (index, row) {
var template = $('#players').html(); //获取模版的html
var bookData = Mustache.render(template, row);//把每行的数据填充到模版得到html内容
playersDiv.append(bookData);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('加载失败');
}
});
});
});
</script>
<script type="text/template" id="players">
<table>
<tr>
<td>球员:</td>
<td>{{Name}}</td>
</tr>
<tr>
<td>位置:</td>
<td>{{Position}}</td>
</tr>
</table>
<hr />
</script>
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
MVC客户端使用 Mustache.js把json数据填充到模版中的更多相关文章
- JS解析json数据并将json字符串转化为数组的实现方法
json数据在ajax实现异步交互时起到了很重要的作用,他可以返回请求的数据,然后利用客户端的js进行解析,这一点体现出js的强大,本文介绍JS解析json数据并将json字符串转化为数组的实现方法, ...
- js读取json数据(php传值给js)
<?php $array =array('fds','fdsa','fdsafasd'); // json_encode($array); ?> <html> <hea ...
- js声明json数据,打印json数据,遍历json数据
1.js声明json数据: 2.打印json数据: 3.遍历json数据 //声明JSON var json = {}; json.a = 1; //第一种赋值方式(仿对象型) json['b'] = ...
- 通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中
摘自:http://blog.csdn.net/mazhaojuan/article/details/8592015 通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来 ...
- JS解析json数据
JS解析json数据(如何将json字符串转化为数组) 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN&q ...
- 初探原生js根据json数据动态创建table
初探原生js根据json数据动态创建table 小生以实习生的职位进入了一家非纯软件的公司做asp.net开发,大半个月下来发现公司里居然没有前端工程师,这令我很诧异,跟着公司做项目,发现前端后台没有 ...
- js处理json数据,java处理json数据
一.js处理json数据 处理办法之一是把本机json数据或远程返回json数据用eval函数,使之变成DOM对象. 例如: var people = { "programmers" ...
- js声明json数据,打印json数据,遍历json数据,转换json数据为数组
1.js声明json数据: 2.打印json数据: 3.遍历json数据: 4.转换json数据为数组; //声明JSON var json = {}; json.a = 1; //第一种赋值方式(仿 ...
- JS解析Json 数据并跳转到一个新页面,取消A 标签跳转
JS解析Json 数据并跳转到一个新页面,代码如下 $.getJSON("http://api.cn.abb.com/common/api/staff/employee/" + o ...
随机推荐
- mac上Python安装和修改Python默认路径遇到的问题
此处例子是我使用homebrew安装了python3.6.1,建立一个符号链接,创建一个python3的命令,达到使用自己安装的python3的目的.此处不修改PATH,而是把需要添加的可执行文件或者 ...
- SqlServer性能优化 Sql语句优化(十四)
一:在较小的结果集上上操作 1.仅返回需要的列 2.分页获取数据 EF实现分页: public object getcp(int skiprows,int currentpagerows) { HRU ...
- 根据条件批量删除document
curl -H "Content-Type:application/json" -XPOST http://localhost:9200/devopsrealinfo/_dele ...
- 【51nod】1934 受限制的排列
题解 这题还要判无解真是难受-- 我们发现我们肯定能确定1的位置,1左右的两个区间是同理的可以确定出最小值的位置 我们把区间最小值看成给一个区间+1,构建出笛卡尔树,就求出了每一次取最小值和最小值左右 ...
- sql结合通配符来自定义转义字符
1.使用 ESCAPE 关键字,定义转义符.在模式中,当转义符置于通配符之前时,该通配符就解释为普通字符.例如,要搜索在任意位置包含字符串 5% 的字符串,请使用: WHER ...
- vwware虚拟机无法连接外网
1.问题:动态IP时连接外网没有问题,但是将IP改为静态IP时发现没有办法连接外网 查看文件/etc/resolv.conf,里面的内容全部都被注释 [root@jenkins network-scr ...
- network出错
1.更改IP之后,执行service network restart时出现 shutting down interface eth0:Device state :3(disconnected)的问题时 ...
- javacript 实现两个数组的差集
<script type="text/javascript"> var array1 = [1,2,3,4,5,6,7,8,9]; var arra ...
- .NET常用的异常类型及其中文说明
基异常类型: 类 说明 System.Exception 所有异常的基类型 System.ApplicationException 发生非致命应用程序错误时引发的异常 System.SystemExc ...
- js数组乱序输出 数组乱序排列
网上看的数组乱序输出,要么不合实际,要么代码繁琐.自己试了下,希望能给大家带来帮助. 重要思想也是Math.random*arr.length随机下标,然后删除取到的元素,继续随机下标. //将数组乱 ...