MVC5中使用ReactJS.NET入门

来源:互联网 发布:vmware mac os 10.13 编辑:程序博客网 时间:2024/05/21 11:03

CommentModel.cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace ReactJS.Models{    public class CommentModel    {        public string Author { get; set; }        public string Text { get; set; }    }}

HomeController.cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.UI;using ReactJS.Models;namespace ReactJS.Controllers{    public class HomeController : Controller    {        private static readonly IList<CommentModel> _comments;        static HomeController()        {            _comments = new List<CommentModel>            {                new CommentModel                {                    Author = "丹尼尔·洛尼格罗",                    Text = "你好,ReactJS.NET世界!"                },                new CommentModel                {                    Author = "China Hunt",                    Text = "这是一个评论"                },                new CommentModel                {                    Author = "约旦·沃尔克",                    Text = "这是*另一个*评论"                },            };        }        public ActionResult Index()        {            return View();        }        [OutputCache(Location = OutputCacheLocation.None)]        public ActionResult Comments()        {            return Json(_comments, JsonRequestBehavior.AllowGet);        }        [HttpPost]        public ActionResult AddComment(CommentModel comment)        {            _comments.Add(comment);            return Content("Success :)");        }        public ActionResult About()        {            ViewBag.Message = "你的应用描述页.";            return View();        }        public ActionResult Contact()        {            ViewBag.Message = "你的联系页.";            return View();        }    }}

Index.cshtml

@model IEnumerable<ReactJS.Models.CommentModel>@{    ViewBag.Title = "Home Page";}<div class="row" id="content"></div>

_Layout.cshtml

<!DOCTYPE html><html><head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>@ViewBag.Title - My ASP.NET Application</title>    @Styles.Render("~/Content/css")    @Scripts.Render("~/bundles/modernizr")</head><body>    <div class="container body-content">        @RenderBody()    </div>    @Scripts.Render("~/bundles/jquery")    @Scripts.Render("~/bundles/bootstrap")    @RenderSection("scripts", required: false)    <script src="~/Scripts/react.js"></script>    <script src="~/Scripts/react-dom.js"></script>    <script src="~/Scripts/showdown.min.js"></script>    <script src="~/Scripts/Tutorial.jsx"></script></body></html>

App_Start文件夹

BundleConfig.cs

using System.Web;using System.Web.Optimization;namespace ReactJS{    public class BundleConfig    {        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862        public static void RegisterBundles(BundleCollection bundles)        {            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(                        "~/Scripts/jquery-{version}.js"));            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(                        "~/Scripts/jquery.validate*"));            // Use the development version of Modernizr to develop with and learn from. Then, when you're            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(                        "~/Scripts/modernizr-*"));            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(                      "~/Scripts/bootstrap.js",                      "~/Scripts/respond.js"));            bundles.Add(new StyleBundle("~/Content/css").Include(                      "~/Content/bootstrap.css",                      "~/Content/site.css"));            bundles.Add(new ScriptBundle("~/bundles/main").Include(               "~/Scripts/Tutorial.jsx",               "~/Scripts/showdown.js"           ));            BundleTable.EnableOptimizations = true;        }    }}

RouteConfig.cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;namespace ReactJS{    public class RouteConfig    {        public static void RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(                name: "Comments",                url: "comments",                defaults: new { controller = "Home", action = "Comments" }            );            routes.MapRoute(                name: "NewComment",                url: "comments/new",                defaults: new { controller = "Home", action = "AddComment" }            );            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }            );        }    }}

Tutorial.jsx

var Comment = React.createClass({  render: function() {   var converter = new Showdown.converter();    var rawMarkup = converter.makeHtml(this.props.children.toString());    return (      <div className="comment">        <h2 className="commentAuthor">          {this.props.author}        </h2>        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />      </div>    );  }});var CommentList = React.createClass({  render: function() {  var commentNodes = this.props.data.map(function (comment) {      return (        <Comment author={comment.Author}>          {comment.Text}        </Comment>      );    });    return (      <div className="commentList">         {commentNodes}      </div>    );  }});var CommentForm = React.createClass({handleSubmit: function(e) {    e.preventDefault();    var author = this.refs.author.value.trim();    var text = this.refs.text.value.trim();    if (!text || !author) {      return;    }    this.props.onCommentSubmit({Author: author, Text: text});    this.refs.author.value = '';    this.refs.text.value = '';    return;  },  render: function() {    return (      <form className="commentForm" onSubmit={this.handleSubmit}>        <input type="text" placeholder="你的名字" ref="author" />        <input type="text" placeholder="说点什么..." ref="text" />        <input type="submit" value="Post" />      </form>    );  }});var CommentBox = React.createClass({loadCommentsFromServer: function() {    var xhr = new XMLHttpRequest();    xhr.open('get', this.props.url, true);    xhr.onload = function() {      var data = JSON.parse(xhr.responseText);      this.setState({ data: data });    }.bind(this);    xhr.send();  },  handleCommentSubmit: function(comment) {  var comments = this.state.data;    var newComments = comments.concat([comment]);    this.setState({data: newComments});   var data = new FormData();    data.append('Author', comment.Author);    data.append('Text', comment.Text);    var xhr = new XMLHttpRequest();    xhr.open('post', this.props.submitUrl, true);    xhr.onload = function() {      this.loadCommentsFromServer();    }.bind(this);    xhr.send(data);  },getInitialState: function() {    return {data: []};  },   componentDidMount: function() {    this.loadCommentsFromServer();    window.setInterval(this.loadCommentsFromServer, this.props.pollInterval);  },  render: function() {    return (      <div className="commentBox">        <h1>Comments</h1>        <CommentList data={this.state.data} />         <CommentForm onCommentSubmit={this.handleCommentSubmit} />      </div>    );  }});ReactDOM.render( <CommentBox url="/comments" submitUrl="/comments/new" pollInterval={2000} />,  document.getElementById('content'));

运行结果如图:

这里写图片描述


这里写图片描述

原创粉丝点击