MVC4中使用React.js入门

本文介绍了一个使用ASP.NET MVC与ReactJS相结合的应用案例,通过前后端分离的方式展示了如何从服务器获取数据并在React组件中展示。文章包含了完整的代码实现,包括控制器代码和视图文件,有助于理解ReactJS与MVC框架的交互方式。

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ReactJSExamples.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return RedirectToAction("Index", "ReactJS");
        }
    }
}

ReactJSController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ReactJSExamples.Controllers
{
    public class ReactJSController : Controller
    {
        // GET: ReactJS
        public ActionResult Index()
        {
            return View();
        }


        public JsonResult GetMessage()
        {
            return Json(new { result = "来自ReactJS控制器的Hello World" }, JsonRequestBehavior.AllowGet);
        }
    }
}

Home视图文件夹

Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

ReactJS视图文件夹

Index.cshtml

@{
    ViewBag.Title = "Index";
}

<div id="content"></div>


@section Scripts{
    <script src="~/Scripts/react/react-0.12.2.min.js"></script>
    <script src="@Url.Content("~/Scripts/HelloWorld.jsx")"></script>  
}

HelloWorld.jsx

 var App = React.createClass({

        getInitialState: function(){
            return{data: ''};
        },

        componentWillMount: function(){
        var xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = function() {
          var response = JSON.parse(xhr.responseText);

          this.setState({ data: response.result });
        }.bind(this);
        xhr.send();
    },

        render: function(){
            return(
                <h1>{this.state.data}</h1>
            );
        }
});

React.renderComponent(<App url="/ReactJS/GetMessage" />, document.getElementById('content'));

运行结果如图:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值