Popular Posts

Tuesday, April 28, 2015

ReactJS.Net in Web Forms App with Server-side rendering


View the complete solution at https://github.com/adamvaul/React-Server-Side-Web-Forms.

I love ReactJS.Net.  It is a framework for managing a React driven website in Visual Studio.  Recently, I got interested in React and wanted to see if I could make it work in a web forms application (not an MVC application like all the demos show).  I got a very simple demo to work based on the Chat tutorial on their website.

In this web forms app there is a little bit of code to render the html string to the page, and then there is a small snippet to add the block to register the react compenents client side.  All of this magic happens with these few lines of code.

I followed the tutorials here at the ReactJS website http://reactjs.net/getting-started/tutorial.html. I also found this article to be helpful but I had to figure out the last part with env.GetInitJavaScript(); on my own.  The article is here at http://xabikos.com/server%20side%20templating/web%20development/2015/03/18/using-reactjs.net-in-web-forms.html

And

In the hmtl:

asp:Literal ID="app" runat="server"

asp:Literal ID="litInitJS" runat="server"



And then in the code behind:

var env = AssemblyRegistration.Container.Resolve();

var homeController = new HomeController();
var data = homeController.Get();
var commentBoxOptions = new
            {
                initialData = data,
                url = "api/Home",
                submitUrl="api/Home/addcomment",
                pollInterval=2000
            };
var commentBoxComponent = env.CreateComponent("CommentBox", commentBoxOptions);
app.Text = commentBoxComponent.RenderHtml();


string initJS = env.GetInitJavaScript();
litInitJS.Text = initJS;

I did not implement all the features like they did, but the application works.

View it at https://github.com/adamvaul/React-Server-Side-Web-Forms.