使用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();
}
[Display(Name = "俱乐部")]
public int ID { get; set; }
public string Name { get; set; }
public IEnumerablePlayers { get; set; }
}
}
创建与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; }
}
}
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)
{
IEnumerableplayersVmList = new List ();
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);
}
}
}
Home/Index.cshtml视图部分:
● 定义Mustache模版,占位符与json数据一致。
● 下拉框触发change事件,获取后台返回的json数据,填充到Mustache模版模版,并把html内容追加到页面。
@model MvcApplication1.Models.ViewModels.TeamVm
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.LabelFor(model => model.ID)@Html.DropDownListFor(model => model.ID, Model.Players)
"playersDiv">
@section scripts
{
}