Populating ViewModels That Are Converted to JSON - json

We are about to break our controllers up: actions that return semi-static HTML pages, actions that return JSON ViewModels and finally actions that post changes. We plan on using JSON.NET to do the JSON serialization since it supports a spiffy LINQ-like syntax for creating complex JSON objects. We will use jQuery+AJAX to call the JSON actions and use the results to replace elements in the HTML.
Before, we were passing ViewModels to the View() method and using it with Razor to fill in the screens. So the real big difference is that our view models will be JSON objects and JavaScript will be building the pages. The problem with the Razor syntax was that it was acting as a crutch. A lot of times we were mangling Razor and JavaScript (Frankenstein). Plus, a few pages take long enough to load that some sort of up-front feedback is needed anyway (loading...).
To the question: I have been looking at my code and have noticed that many ViewModels share common properties. Furthermore, the same logic is appearing across multiple controllers. I have been wondering what patterns/tools are out there for putting this logic into one place. Also, should I be trying to create a "master" ViewModel with child ViewModels (with other child ViewModels and so on)? The idea being that some elements are shared across all pages (such as header and footer content) and so it would seem to make sense to have a common ViewModel structure for each page. That way I can reuse the some JavaScript for finding data and setting it in the HTML. I figure if a page doesn't use a child ViewModel, I would just pass null, so it wouldn't take up too much space.
I want to make sure that I get things right before I start going down this new path. I have seen applications that use the hierarchy of ViewModels before and have seen problems because of it. I also want to keep the number of AJAX calls down, so I want to return as much data as possible in as few calls as possible. They are kind of contradicting requirements. I was hoping someone had experience with building lots of ViewModels and and with converting these to JSON objects for consumption on the client side. I was also curious if anyone found any tools for JavaScript for building pages from ViewModels. We are looking at backbone.js right now, but it seems oriented towards forms rather than generic content generation.

The idea being that some elements are shared across all pages (such as header and footer content) and so it would seem to make sense to have a common ViewModel structure for each page.
You should consider using partial views and master pages to accomplish this if you aren't already. Both are very useful and powerful tools.
I was also curious if anyone found any tools for JavaScript for building pages from ViewModels.
An extremely powerful JavaScript library that uses the MVVM pattern is Knockout.js. The twenty minute introduction video on the home page explains it very clearly.

Related

Right way to embed HTML Pages to angular app

I am building my own website with Angular2 coupled with Spring boot and postgres as Backend.
The login/logout features are built to perfection but I have trouble understanding how to develop a site like geeksforgeeks where there are multiple links in a page and each page hosts different kind of content.
The idea is large scale and I intend to have lot of pages(topics) as I develop further.
My question is :
1)Should I be creating as many HTML Pages
2)Or What is the standard way of doing it.
I just want to know the right direction, have been scratching my head for quite some time with unsatisfactory solutions.
You should not create as many HTML pages.
Plan to make a category of your type or section of posts
Define templates for each category (e.g. Review something, generic blog post, some solution, etc)
Get the post json from backend along with section or type
Bind it to preferred template to your view

Designing/debugging complex data binding graphs in polymer

As far as I can tell, most of the talks and resources on Polymer cover fairly trivial cases of data binding.
However, Polymer is a powerful tool that can in principle be used to build things like IDEs, WYSIWYG editors, or even simple games; as long as the total number of elements on the page is kept fairly small (certainly <1000, but ideally <100).
However, in these examples, the graph of data bindings can become very complex, and the results of a single event (e.g. a mouse click) can propagate/reverberate around the binding graph in hard-to-comprehend ways.
So, the question is, firstly are there any resources (videos/blogs etc.) that discuss best practices etc. for these types of complex scenarios; and two is there any chance of having a tool which generates a graphical representation of the binding graph. Ideally such a graph could be rendered in the page, superimposed on the elements themselves. In fact, one could imagine having a "record" feature, that tracked data propagation during an event and generated a GIF showing the data moving around the graph.
This may not be an ideal question for SO, but it didn't seem right as an issue on github either.
That's the reason why you should use an external state management framework such as redux for complex apps.
You can use the polymer-redux behavior which is a simple behavior that allows you to interact with redux.
You basically split up your components in Presentational and Container Components. The presentational polymer components are your leaf components that are unaware of redux and only take in data and emit events. The container components implement the redux behavior and dispatch actions for state changes and pass data to their childs (usually presentational components).
The state is stored globally and all the state modifications happen in reducers that you can easily unit test. The advantage is that you can use the redux-devtools to do time travel debugging and also visualize your state as a graph

Is Knockout.js inline with content/UI/behavior separation best practices?

I've been working on the web for quite a long time and I saw the "best practices" evolve. I'm now fairly convinced separating HTML (Content), Javascript (Behavior) and CSS (UI) is the best thing to do.
A few months ago, I started using knockout.js . I did choose it among other similar frameworks like backbone or angular because a chapter in an MVC training I followed was about knockout, and the concept seduced me. Then after a quick comparison on the web it didn't look as a bad choice for my needs, and for a start.
But here's my problem : when I look at my HTML code now, after a few weeks of dev on a project, there's quite a lot of knockout bindings in it, and it makes me think a lot about the old times, when we (or at least I) used to put inline javascript event handling through onclick attribute and so on.
Therefore those 2 questions, which I'm not sure are 100% suited for SO, but I can't find any better StackExchange site to ask it :
Is using knockout (or the other frameworks as they all seem to basically work with the same pattern) contrary to the "separation rule" ? Or is it an acceptable small-step-out of this rule ? or is it even perfectly acceptable because it uses the "data-" attributes ?
In the case this would be a somehow bad practice, is there any possibility to do all the binding through a separate javascript file, using for example jQuery to select the controls and apply bindings to them ? If not possible in knockout, is it with another framework ? I must admit at the time I did my selection, I diddn't think about this kind of implications...
Thank you and sorry if this should be moved to another SE site.
I had the same initial reservations as you, but I have to say that having the bindings in the html and not hidden away in a JS file seems so much better to me, as the link between presentation and functionality is now completely obvious. It massively reduces the possibility of changing some HTML and breaking functionality because you weren't aware that someone had hooked up some javascript to an element using jQuery.
Also, as you point out, the use of the data-bind attribute does, I think, mean that it does adhere to the separation rule, though if you want to stick to it rigidly then make sure all bindings are to observables, computed or functions on your view model, don't use any code (i.e. a visible binding that checks the state of two observables). I'm not sure I'd take it that far though.
I guess everyone started to learn KnockoutJS have the same concerns.
IMHO, there must be some way that connects models(JS object) with views(HTML markup). Then we should have something that says:"When that button is clicked call this function with that arguments." or "Hide this element while you that JS array is empty" and so on. So how we can put/say/state that connection in a readable, reusable and clean way.
If you used another JS file to handle that connection, then you 'll have large lines of code just to put your connection logic and you need to know how to select the DOM element you are targeting. You 'll end up with massive code(probably lot of jQuery) just to make your HTML dynamic and alive(i bet most developers got into that many times). I haven't use other libraries or frameworks but i think they just make your massive code more organized.
On the other hand by KnockoutJS use Declarative Bindings, this is the link between models and views. It's more readable, easy to plug it in/out and it allow you to just focus on writing a good JS model object.
I guess to truly check separation think what if you sometime needed to change your model, how much changes you need to do to your view? and vice versa?
Adding to the rest of the answers, some tips:
Make sure there's no business logic in your bindings. Any logic (which should be minimal) should be "view logic": decisions that only affect how your view looks, not how it works. Deciding how many items to display per screen is view logic; deciding whether the user can add another item is business logic. It's perfectly OK to put view logic in your viewmodel rather than your view, and it's desirable if it involves lengthy expressions.
Keep "magic numbers" out of any view logic in your bindings. If it's a parameter that could be changed (e.g. number of weeks of results to show) as opposed to a true constant (e.g. number of days in a week), make it a property of your viewmodel and reference it in any expressions in your views.

Would you consider HTML + CSS + Webserver to be MVC?

Simply put, MVC is the pattern for separating contents (model) from presentation (view), and having a mechanism in place (controller) defining how to gather both.
If you already see where I am going at, I am very interested to hear your opinion on the matter. Of course, MVC applies to serverside mechanics and all, but think out of the box here with me for a second.
"Visitors" of the web, both human and robot/Google will be likely to see HTML and what comes with it. Writing structured and meaningful HTML, together with separating it from presentation using CSS has become more important over the years, and future technology such as HTML5 only contributes to this separation by offering a more content-focused set of elements, and mechanisms for working with the pure visual representation.
Considering all this, I was wondering if it would be correct in some way to say that the MVC paradigm applies to the front-end as well, where:
The model would be HTML, as in the pure httpwise contents that it has become
The view being CSS; it makes your content be presented a certain way
The controller being the webserver and all that lies underneath, it is what gathers and separates the model and view, and does all the decision making
Makes sense? Not?
VonC pointed me to an article that definitely changed my thoughts on the controller part. The browser takes up a major part of the controller too, as it handles a great deal of user interaction and how the model and view work together.
You can generally find MVC in anything if you look hard enough.
I would agree, although one can argue about the controller.
Jeff illustrates that point in his post, with ZenGarden
With:
Model = HTML
View = CSS
Controller = Browser (which is more 'front-end' than the web-server)
Actually, this is a valid perspective from the client-side.
From the server side (a server more complex than a simple html-page server), MVC would be different.
With ASP.Net for instance;
Model = all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic and database access logic. For example, if you are using LINQ to SQL to access your database, then you would create your LINQ to SQL classes (your dbml file) in the Models folder
View = HTML markup and content that is sent to the browser, plus scripts
Controller = responsible for controlling the way that a user interacts with an MVC application. A controller determines what response to send back to a user when a user makes a browser request.A controller is just a class (for example, a Visual Basic or C# class).
That is a services-ide perspective of MVC
No, sort of...
Your HTML is also at your presentation layer (View), although your CSS should contain the presentational specifics like fonts, colors etc.
Your Model must contain your data + business logic, and I really don't hope that you'll want to store these in HTML - that's for real programming languages, stored procedures and a DBMS to handle. And these should be at server side.
But to follow your line of thinking, I would suggest:
Model: Server side programs + DBMS
View: HTML+CSS
Controller: Webserver
I can see your point, but I think I would describe HTML-CSS-Server/Browser more as Document-Viewer rather than MVC. If all of the content is static then it is an expression of the model, true, but the model is embedded in mark up. Even though I can override it with CSS, CSS is really just a filter on the underlying presentation described in HTML. The HTML describes a view of the data as well as the data itself. To wit, I can turn off CSS and I still have a view of the data. In MVC, this is not possible.
There is also a close coupling between your HTML and your CSS -- both need to be very aware of the other. This violates a key paradigm of MVC where the components are loosely coupled. In particular the view enforces no constraints on the model (other than the restriction that the data be viewable). HTML designers are constrained to operate within the domain of the CSS or to modify the CSS to make it applicable to the domain of the HTML.
Further, HTML has no way of operating on the data to make persistent changes. A key aspect of the model is the ability to enforce business rules. HTML does not do this with static content -- the web designer does by the choice of the HTML encoding.
This doesn't make it bad, or not useful. Not everything has to be MVC. MVC simply describes one particular way of organizing your data and code. It has some particular advantages with respect to decoupled architecture and testability, but that doesn't mean that it is the only valid architectural pattern available.
Static HTML content, in my opinion, isn't MVC and doesn't need to be.
[EDIT] I am not arguing that you can't use MVC in the design of a browser, or that MVC isn't applicable to the the display of static content in a browser. I'm really looking at this from the perspective of the content provider, not the browser programmer. MVC could be a perfectly logical choice for browser design.
CSS is definietely not the view. Rather the rendering by the browser (which combines HTML/DOM and CSS input into a 2d layout) is the view. The HTML/DOM is the model. The controller is halfway built into the browser UI, but can be extended with javascript.
It is true that CSS is considered the presentation layer when talking about the content/presentation seperation - however that is a different (orthogonal) model.
In MVC, CSS is part of the model along with HTML/DOM because it is the underlying data which can be rendered in different views. For example, a print layout is a seperate view based on the same model.

Creating a web application, then adding Ajax to it?

I imagine there are many of you out there who have developed an application online which automates a lot of processes and saves people at your company time and money.
The question is, what are your experiences with developing that application, having it all set in place, then "spicing" it up with some Ajax, so it makes for a better user experience?
Also, what libraries would you suggest using when adding Ajax to an already-developed web application?
Lastly, what are some common processes you see in web applications that Ajax does well with? For example, auto-populating the search box as you type.
My preferred way of building Ajax-enabled applications is to build it the old-fashioned way where every button, link, etc. posts to the server, and then hijack all those button, link, etc. clicks to the Ajax functionality.
This ensures that my app is down-browser compatible, which is good.
It doesn't really matter which you use, unless you're trying to do something very specialized.
Here's a good list: http://code.google.com/apis/ajaxlibs/.
Yes, auto-completers are a pretty handy implementation of Ajax. It's also quite useful for data-intensive activities like populating drill-down data.
A lot of what you can do with these libraries isn't Ajax-specific, there is a lot of UI interaction that can benefit the user as well. You can do things like slideshows and lightboxes quite easily with many of these libraries.
Pick the one that you're comfortable with. The syntax they all use is a little different. Give a few a spin and try to build simple examples. Stick with the one you like.
Using ASP.NET Ajax to wrap a few chunks of code is an easy way to get going. But personally I prefer to use jQuery. You can easily add some simple Ajax calls with it to make the UI more responsive without the ASP.NET Ajax overhead.
If you are using ASP.NET to write your applications, adding AJAX using ASP.NET AJAX is very straightforward and in many places will not require you to change any code at all except add two controls to the pages you want to modify.
This works using partial page loads. The controls you have to add (off the top off my head) are called something like
<asp:ScriptManager
and
<asp:UpdatePanel
The biggest thing I use for AJAX is lists and search forms. Why? Because the overhead of loading an entire page when you are going though a list of, let's say, 200 records, it will get frustrating for a user to go though everything. However, it is important that if you click on a link in the page and then hit the back button or use a link at the top to return to the same page you were on.
For search forms, as you fill out the form I use AJAX queries to return the first few results and a number indicating how many records that were returned.
For AJAX frameworks, I use mootools. http://www.mootools.net.
Please ignore if not using ASP.NET. Your platform wasn't clear from your question.
Depending on when you created your web application, your web config file may need some tweaks to use ASP.NET Ajax. The easiest way to see is to create a new web site with the ASP.NET Ajax template and compare the web config, copying over configuration items as needed to bring the old one up to date.
If "spicing it up" is all you're after then develop the fully functional app without AJAX first. From here you can unobtrusively add AJAX functionality and ensure that the app degrades well for non JavaScript-enabled browsers.
I've started using jQuery for JavaScript on my site. It takes away all the worry of cross-browser JavaScript differences - things like class and classname, and getElementById. It also includes some very handy and simple functionality for AJAX postbacks. It's very easy to learn and extremely lightweight when used well.
I've seen some good use of AJAX right here on Stack Overflow, things like the tag selector and the question lookup when you type a question title. I think these simple things work best; we're just adding to the user experience with small additions to functionality that are intuitive, we're not flooding the screen with drag/drop handles etc.
I would differ from the first poster. Adding Ajax isn't always as easy as 1,2,3. It really depends on what you are after.
Adding things such as a colour animation can be made fairly easy, but if you are after things such as auto populating a text box, this requires extra code. It's not as easy as adding just something client side. You would also need to add in server-side support to fetch the partial query results.
Going beyond that, it can become even more complex keeping your client-side script in sync with server-side support.
But with the spirit of simplicity in mind there are libraries you can use to 'spice' up a website with animations and other eyecandy that can be implemented fairly easily which have been mentioned already.
I've often had to Ajax-enable an old-fashioned ASP.NET 2.0 sites. The easiest way I've found to do that is to create a new Ajax-enabled site and copy and paste certain sections of the web.config into your old project's web.config.
Just compare the two and see what's missing in your old one. You'll obviously also need to add references to AjaxExtensions and AjaxControlToolkit.