g:include vs g:render - grails

I have a question about pros and cons of g:render and g:include.
In my application I have a piece of code that shows some information that have to be repeated in some gsp, what it show depends on a little bit of logic.
I have a doubt is it better use a g:include or a g:render???
So, is it better to execute the logic on a controller that pass a model to the page that use a layout included with the g:render, or is better to put a g:include to another action in another controller in the gsp that execute the logic of that piece?
I prefer the second choice, but how much it impact on the performance?

They are just used in different cases. You use <g:include .../> when you have a controller that is returning a piece of content that is easily embedded in multiple GSPs. This is also useful if you have a high volume of traffic where you are actually caching at the controller level since you can eliminate a lot of overhead.
<g:render.../> is useful when you need modularity within your page. Especially for AJAX calls where you may initially load one portion of the page then want to update it based on some AJAX event.
Both can be used to reuse content, and both are appropriate in the right context.

g:render is useful while you are working on partial templates and you have the model you need etc.
However, when you need additional (or extensive) progress to pass extra, more meaningful things to your view(template), it is better to use g:include.
By using g:include you will also have a nice controller and that means much more readable code using that controller.
And there would be no performance comparison between 'passing to a controller action and render a view with doing no additional operation' and 'render a view'.

Related

Multiple Views Same Model

I have a Course Model which goes the controller and views in a restful way.
For my Course show, it is fully featured. I now want another Course show which will have a simplify page and it like to the original course show.
How can I implement this? I want it to be restful, so in my controller there should only be show, update, index, etc.
Should I create another controller that have an different name from the Model? E.g. Course2?
If it is an admin view vs. public view, I would have entirely different namespaces for two different RESTful controllers. Or if you think you're going have this summary vs. full view thing a lot, create namespaces based on that distinction.
Another option is to encoded the differences in a single ERB template. Or you could actually have the show action render different templates from the same action using some conditional logic.
Without more context though, I can't really say what's the best option. I am personally against creating non-RESTful actions unless it's really going to be a one-off thing. Non-RESTful actions tend to get out of hand in my experience and controllers can get really ugly and unintuitive.
If this is truly just displaying a subset or a different arrangement of the same information, then I think this is a job for the view. At most the controller can use the same action, but select a different view to render, such as might be done if the user wanted to see html vs plain text.
The controllers job is to interpret the model and the views job is to collect and display information. I think you would be concerned about the view having logic in it if you what you describe as a "summary" were more than just a subset of the info, for example if you started to calculate the distances being traveled or how long it would take or how much it would cost based on the data that is provided, then that would be bad.
So I this is just a subset, then I would suggest either rendering partials based on some variable set by your controller, or if organization of the display needs to be substantially difference, then the controller can select a different template to render.

Page initialization patterns with ASP.NET MVC and MVVM like knockoutjs

When creating an interactive form or other kind of web page, there are a couple of options with knockoutjs. One could create a strongly-typed view and pass a model to it from a controller. On the other hand, one could just as easily start with a plain old html document, and have it initialize itself by calling action methods (JsonResult or otherwise) after the initial load.
Also when starting out the page as an MVC view, you could use HtmlHelpers along with plain old html markup to initialize the view. Another option is to serialize the model state as json to a hidden field, and use that to initialize the view.
In my experience, during first load, there can be a delay when you let ko initialize the view. Whether you construct a viewmodel by passing json from a serialized hidden field, or rely on it to invoke various services to load the data, there is a moment before the page is "ready". These kinds of delays can be avoided by initializing the page with HtmlHelpers, etc, but such initialization could also incur additional costs (extra initialization logic in the controller, default content in the views, etc).
Which way of initializing a page is the most MVVM? Is it a bad idea to use HtmlHelpers in the views, or to use cshtml at all? If not, where do you draw the line between view and viewmodel?
"The most MVVM" is a hard question to answer, especially considering that we are already mixing patterns with MVC and Knockout.
I would think that letting Knockout do all the work of initilization would be "the most MVVM", but rigid adherance to a pattern when you are having issues is not a good idea. If KO setting values after the DOM is ready causes problems that you can fix by letting the HtmlHelpers initialize the page, then do what works. Since the HtmlHelpers will let you set the data-bind attributes at the same time, this feels like a good solution, and I have done this before with good results.
I would say that storing JSON in a hidden field is not a good idea though. You can directly encode your model into JSON by using this in your javascript:
var initialData = #Html.Raw(Json.Encode(Model));
This is a good solution since the page starts out with the data your controller sends it, without needing a second request.
You may have to think about what trade-offs you want to make. If you want purity and no code duplication, you might have to accept the issue of KO taking a little time to initialize the page. If you want a perfect User Experience, you may have to sacrifice a little purity.

ASP.NET MVC - How to best build a form action that can respond in many ways?

I am in the process of writing a web app that includes a reporting form. This form contains a number of radio buttons that allow the user to specify the return data.
There are about 6 different return data 'formats', and each of those has two variations - html data or JSON data for rendering to a chart.
I have begun coding it up and already my form post action method feels wrong.
I basically have a check on the requested data format and return it as needed. Each return type requires its own partial view / json object so there is little room for reusing code.
It feels like each one should have its own action method. Having the form post to different locations based on a radio button choice also feels wrong though.
Switching on report type and then redirecting to the appropriate action in the controller also feels like its not quite right.
Am I approaching this in the wrong way? As it currently stands my controller action contains a lot of code and a lot of logic...
Hope my query makes sense.
Thanks
I don't think there is anything wrong with your approach. To maximize reuse you could:
include reusable templates inside your views
make sure the business/data layer code is the same everywhere (where possible)
I suppose the views you need to return actually are different for each combination of options so whatever approach you take, you are stuck with that.
I wouldn't opt for the client-side approach. You then have code on both the server and the client that has to be updated whenever you change anything. I would keep the code that receives a set of options and determines what to do with them in one place.
I know what you mean about it feeling like each format should be a separate action, but maybe a hybrid approach would make it feel better.
If you set the value of each radiobutton to the name of the action it relates to, you then, in your main POST action, have a parameter that you can use to call the appropriate action in one line of code. You don't have to fudge anything in Javascript, it's easily extensible, and you get your separate actions.
If I understand your problem right you have a lot of switch code in action.
I think you can use Factory pattern. You can create factory that will accept switch parameter as parameter and will return ActionResult instance.

Rendering Navigation in MVC3

What's the best way to render Navigation in MVC3? In my app the Controller has to decide what should be in the Navigation but as far as I know there's no way to pass a Model up to the _Layout file (where the Navigation html lives) to give it this information.
You can make the model available to your layout.
Define a base class, MyBaseModel, with the properties you want available to the layout.
Have your models subclass MyBaseModel, and ensure that you populate the properties
Have your layout specify #model MyBaseModel
Use the properties
See also this blog post where a similar problem ("we often find ourselves needing to include the same information in every page") is tackled.
Best is a relative and subjective term. I would usually go with an approach similar to druttka's answer but another option is to use RenderAction() to invoke a controller action
<div>#Html.RenderAction("action", "controller")</div>
I will offer some counterpoints to #druttka's answer. But mostly, you have to decide which trade off you want to make.
If you use a model for your view, you are now forcing 2 things:
Every view must be strongly typed
Every action must call the function to populate all levels of nav included in your view model
The first point isn't so bad, because there are very few pages in a typical non-static site which wouldn't derive from a model anyway, and its easy enough to create an empty model for those pages. The second point is much more annoying however. Each function has to instantiate it's own model, and then populate the nav properties for every level of nav provided by the model. This can be quite cumbersome, but can be fairly elegantly handled in OnActionExecuted for at least nav which is not specific to a given action.
The alternative is to add the nav to the ViewBag. This can be done whenever and does not force you to specify a model for every view, which is great for the flexibility in those cases where you do not need to specify a model. It should be noted however that the ViewBag in asp.net mvc 3 is of type dynamic, which you cannot use as a parameter in a lambda function, thus preventing you from doing something like #Html.DisplayFor(viewBag => viewBag.MainNav) in your layout, which is a real drag. You can still render partial and specify the appropriate DisplayTemplate however.

ASP.Net mvc building an xml data feed for a chart

I have to build an xml output that represents a data structured for a flex chart placed in the view.
I have several options:
have the controller create the xml (using data from the DB), and return it to a view that actually does nothing, since everything is ready.
have the view strongly typed to the data model from the DB, and render the xml declaratively in the view.
create an Html extension method that will contain the logic to create the xml and use it on the view.
in terms of separation of concern, what would be the best option?
in the future I don't expect many changes to the xml structure, maybe now and then.
I tend to select option 1 as it is more testable, and I feel more comfortable with the controller preparing the xml data.
I'd go for option number 1, as I feel it fits the MVC pattern the best. It's not the responsiblity of the View to create an XML file based on some data model. That's business logic and is therefor better off in the controller.
And equally important like you say, if you have your controller create the xml file you can create a unit test for it that asserts that the output xml is valid, contains all necessary nodes, etcetera.
Option 2 is the best. Your model has the data, your controller asks for it and offers it to the view. The view just has a tag to say where it goes. That to me is separation of concern.
Seeing Razzie's answer, I liked 1 as well, and I suppose that the model would have to provide some method for serializing some entity class (your chart results) into xml, in order for your strongly typed view to be able to make use of it.
Anyway I hope the answer helps, basically I don't think 3 is very good. :-)
I would say it depends on what you are more comfortable with as both options 1 and 2 are viable. People will say that option 1 is good as you can use an XmlWriter to make sure you've got valid xml to be returned and people will say option 2 is valid as mvc is all about having complete control on what is rendered in your view (which can be xml).
However, I would personally go with a variation on option 1 to keep the functionality independent of the controller and have it as a standalone utility method which takes in the data and outputs the xml. This will be easier to test but also be available to be called from other places in your code if this is needed in the future. In addition to this it also keeps the code in your controller cleaner.
And I agree with Mark I don't think option 3 is a good way to go.
That's just my thoughts, hope this helps :-)

Resources