ASP.NET MVC Reuse Partial Views in Ajax

I wrote a sample web application which demonstrates how ASP.NET MVC partial views can be reused for loading content via Ajax. The most popular scenario nowadays is when you want to load a content via Ajax you’ve to create a HTML template where you’re going to pass the data and apply it to the web page. Well, I think that we must think for the simplest and easier way for managing templates into our web apps.

We already have write once the HTML template by having partial view! The partial view exists and I don’t want to write any HTML with concatenating strings in JavaScript scripts.

I still follow the principle by using one data model and one and the same partial view. I do not load the data by applying different HTML template via Ajax.

As you see on screenshot below the data that is highlighted with red is loaded when the entire web page loads. There is Razor partial view which visualize the model that I pass to it. So, I have a form as well and I want to submit the content and show on the first position before the other.  I have the option to copy the HTML from the Razor partial view and concatenate it with the data that will come via REST and apply with jQuery to the web page. I don’t want to do this and that’s why I wrote a Razor engine view parser which helps me to reuse existing partial view as a template.

 

Dynamic Templates

I’m quite sure that this implementation can be done better but I just wanted to make it happen before I forgot to implement it.

As you see the partial view is exactly the same.

In this implementation I use jQuery only for making Ajax calls and load the data in the proper HTML position. There is no HTML concatenation and repetition of the code which I use for the articles.

Dynamic TemplatesI created a GitHub repository where you can look at the code.

I believe that the code needs to be improved and tested before you want to use for any apps. I just wanted to demonstrate that it’s easy to reuse existing source code. I hope you will find it useful.

 

1327 views