The MVC client uses Mustache.js to populate the template with JSON data

Source: Internet
Author: User

The advantage of using mustache is that you can define some of the reusable HTML parts as mustache templates for multiple use. The approximate steps for using mustache are:

→ Get json data from the background
→ get foreground page pre-defined mustache templates (placeholders must be consistent with field or property names coming from the background)
→ Iterate through each line of JSON data, using the Mustache.render (template, Row) method to populate the corresponding placeholder with the JSON data, to get the HTML content
→ Append HTML content to a location on the page

Displays a drop-down box for a football club:

When clicking on the dropdown box, show the player of the club:

To create a CLUBMODEL.EDMX model, team and player are 1-to-many relationships:

Update the data in the model to the database and add some data to the database:

Create the ViewModel that corresponds to the team as TEAMVM.

using SYSTEM.WEB.MVC;
namespace MvcApplication1.Models.ViewModels
{
     Public class Teamvm
    {
         Public TEAMVM ()
        {
            New List<selectlistitem> ();
        }
        "Club")]
         Public int ID {get; set;}       
         Public string Name {get; set;}
         Public Ienumerable<selectlistitem> Players {get; set;}
    }
}

Create the ViewModel that corresponds to Plyer for PLAYERVM.

using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models.ViewModels
{
     Public class Playervm
    {
        "Players")]
         Public string Name {get; set;}
        "Location")]
         Public string Position {get; set;}
    }
}

HomeController Section 2 controller methods, one display drop-down box, a response drop-down box of the Change event.

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
    {
        Show the team to the drop-down box
         Public ActionResult Index ()
        {
            New TEAMVM ();
            using New Clubmodelcontainer ())
            {
                var teams = context. Team.tolist ();
                New SelectListItem ()
                {
                    Text = T.name,
                    Value = t.id. ToString ()
                });
            }
            return View (TEAMVM);
        }
        Response drop-down box
         Public Jsonresult playersbyteamid (int ID)
        {
            New
            using New Clubmodelcontainer ())
            {
                var players = context. Player.where (x = X.teamid = = ID). ToList ();
                New PLAYERVM ()
                {
                    Name = P.name,
                    Position = P.position
                });
            }
            return Json (Playersvmlist, jsonrequestbehavior.allowget);
        }
    }
}

Home/index.cshtml View section:

Defines the mustache template, which is consistent with the JSON data.
The drop-down box triggers the Change event, gets the JSON data returned in the background, populates the mustache template template, and appends the HTML content to the page.

@model MvcApplication1.Models.ViewModels.TeamVm
@{
    "Index";
    "~/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 ({
                    false,
                    "GET",
                    "@Url. Action ("playersbyteamid","Home")",
                    "id": ID},
                    Success:function (data) {
                        "";
                        Playersdiv.html (");
                        $.each (data, function (index, row) {
                            var template = $ (' #players '//Get template HTML
                            var bookdata = Mustache.render (template, row); //Populate the template with data for each row to get HTML content
                            Playersdiv.append (BookData);
                        });
                    },
                    Error:function (XHR, ajaxoptions, Thrownerror) {
                        Alert (' load failed ');
                    }
                });
            });
        });
    </script>
    <script type="text/template" id="Players">
        <table>
            <tr>
                <td> player:</td>
                <td>{{Name}}</td>
            </tr>
            <tr>
                <td> location:</td>
                <td>{{Position}}</td>
            </tr>
        </table>
        
    </script>
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.