How does Orchard get away with no call to RenderBody? - asp.net-mvc-3

I’ve been dissecting the Orchard CMS rendering and view engine in an effort to understand how it’s put together. I have discovered that neither RenderBody nor RenderSection are ever called. It is my understanding that the Razor view engine requires a call to one or the other.
What is it that gets around the requirement that RenderBody or RenderSection have to be called or an exception is thrown by Razor?
Is it the fact that there’s a custom view engine (ThemeAwareViewEngine)? If so, how does it handle parsing Razor syntax to generate the content?
Thank you.

It's actually the other way around. Razor itself doesn't require that RenderBody be called it's the RazorViewEngine that has this requirement. There can definitely be another view engine that uses Razor that has a completely different way of working. Take a look at https://github.com/Antaris/RazorEngine or https://github.com/Buildstarted/RazorSharp I've also written a markdown view engine that uses razor for some simple layouts.
From reading the source it looks as if they've created a few custom view engines. Their RazorViewEngine replaces the base class for razor generated files with their own custom WebViewPage which has a method Display of which Zone is an alias for. This is what allows them to render child views in addition it seems as if there are several types of Zones within the LayoutAwareViewEngine such as DocumentZone, ContentZone and so forth.
So in the end they've done a lot of custom code.

Related

a rails partial but used by multiple views

I have a piece of code that I would like to have show up on several areas... from two different views. Which is to say handled by two different controllers (all the data comes from a helper though) what is the best way to break this up, should these partials be rendered then as lay outs? Though they use the twitter bootstrap modal and I have had huge issues getting those to show correctly when called from a layout (most the reason why I have to break up this code into a partial, one that comes from one index.erb.html and another that comes from a partial of its own _document_header.erb.html good time to ask, can you stuff one partial within another...
so just trying to get some pointers. This code is really common to two views.
(and is not always needing to be rendered or displayed)...so want to do this the best way.
You can reference a partial that is anywhere in your views folder.
It's common to make a "shared" folder in your views and reference the partial like: <%= render 'shared/my_partial' %>

How much server side code in MVC views

I have been developing MVC 3 applications using Razor. I was wondering how much code would be acceptable in my views. There were situation where I needed to create, instantiate and use an object which wasn't included in the model and using ViewModel would make the model object bloated. Now when I look at some of my views, I find them full of server side codes. What would be the best practice when dealing with such issues?
I was wondering how much code would be acceptable in my views.
If by code you mean C# code then there should be exactly 0 to be precise. On the other hand it is perfectly fine to write HTML markup in your views and call HTML helpers.
There were situation where I needed to create, instantiate and use an
object which wasn't included in the model and using ViewModel would
make the model object bloated
Then it seems that your view model was not adapted to this view (since this view requires additional information). So change this situation by adapting the view model to it and including everything that it needs.
Now when I look at some of my views, I find them full of server side
codes. What would be the best practice when dealing with such issues?
Yes, that's horrible. Simply adapt your view models and refactor this code into your view models or controllers or even write custom HTML helpers.

With regards to Html helpers, does data access code go into the helper class too?

I am writing a helper class to query my Zenfolio feed, return and display the images. Right now this code is split between a viewmodel and code in my controller. I want to pack it up into a helper class. Would all the code go into the helper or do i still split the code among different class with the helper only responible for generating the html? I have googled but not found an answer to my question.
Within the MVC pattern there is a clear separation between Model (data), View (html) and Controller (what gives the Model to the View).
To answer your question, No. Load your models in your Controller. Display them in your View. Html Helpers should only generate html for your view.
You may want to consider using a DisplayTemplate, which allows you use the same View template for every model of a particular type.
I wouldn't do any data access from the view. This sounds like a good use case for an action, and reusing code via the RenderAction method. You can mark the action as a child action using the [ChildActionOnly] attribute, which ensures it can't be invoked directly from the HTTP request, and return a PartialView result.
HTML helpers should really be used to generate HTML tags from data taken from the ViewData or Model (i.e. your view model in this case).
Data access in an HtmlHelper is only pain.
I've had the misfortune to inherit a project that had ad-hoc SQL placed into the HtmlHelpers by the 2nd developer on a project. The HtmlHelpers were beautifully written by the first developer, and the ad-hoc SQL pretty much nullified all of the time and effort put into having an service oriented architecture, having an ORM (the 2nd level cache became worthless), the unit of work pattern(transactions, worthless), and every aspect of design. Eventually, this 2nd developer had to make larger and larger HtmlHelpers so that different elements could share access to the data.
This was originally done for a display mode, and editing was accomplished through a pile of ugly custom javascript. All told, when the page rendered, it made 600 synchronous calls to the database.

Question on using content from other cshtml pages in razor

I've read a couple of articles on using asp.net mvc3 razor (which I am fairly new to). I have a couple of .cshmtl pages which are like shared content (e.g. header). They are basically just html pages with one or two divs etc.
To embed this in my main page, do I just use #renderPage("page address"). Do I also need a call to #renderbody? Do I need to specify the/a page in the layout property?
Thanksa
I would put the common elements in a layout (or perhaps a partial view rendered by the base layout). In fact, that's what I did in an application I am now building and it works quite nicely. The one issue is whether or not you need View Model data populated by the controller and passed to that partial view. I did, so I used a base controller and populated the common elements in the view model (all of those also inherited from a base class that had the common properties) and used sections and then in the sections renderered the partial view or not, depending on the view's need.
You can create a Partial View for each of these and call:
#Html.Partial("ViewName")
Or you can use sections, or this article on sections might help too.
As you may or may not know, ASP.NET accepts HTML tagging.
So why not include your .aspx file with the HTML include tag?
Here's how:
<!-- #include virtual="path to file/include-file.html" -->
Ex:
<!--#include virtual="header.aspx"-->
I do this all of the time when writing an ASP.NET website.
Just place it wherever you want the code, from the included page, to show up.

How to display multiple widgets on the same page using MVC

I'm a bit confused about how MVC works and I can't find anything but basic examples.
I want to make a kind of widget-based design; you can choose various widgets to go on your page. Each widget should be responsible for itself - it should have a controller and a view. But what about the main page? Suddenly I've got a page with lots of controllers on it!
The obvious thing to do is to embed the controllers in the view somehow... This is my widget {SomeWidget} but I've read that "breaks the MVC paradigm".
Some widgets will need to POST to different urls (like a search box goes to the result page) and some will need to POST back to the same URL (like adding a comment to an article brings you back to the article).
To top things off, the user should be able to edit the HTML around the widget - for example if they want a search box on the right, they can type <div style="float: right;">{SearchController}</div> (in my paradigm-breaking world)
I am not very good at web programming, but i believe, from the example you described, that there should be one model, one view and one controller for the entire page. Now the view itself should contain the views for every widget in the page (and the same goes for the page controller) to which it dispatches the messages it receives.
Conceptually there is a lower level of MVC (for widgets) and a higher level of MVC (for the page). And the MVC paradigm won't be broken. Now you can edit the HTML around the widget, it changes the page model (and not any widget model).
Hope this helps !
To add to #Benoît's comment:
The Symfony framework handles this with components. Each component is a self-contained MVC instance that can be embedded into another view. It cannot be instantiated to respond directly to web requests like the normal MVC instance (a module/action pair). It can only be embedded into another MVC view.
As a side note: Symfony also treats plugins as their own complete MVC instance, complete with its own schema, models, controllers, config files, views, et al.
In your case, each component would be its own MVC instance and the app would stitch these components together. Each component would be responsible for how it responds to a form submit.
MVC doesn't mean there is ONE view and ONE controller. It just means the app logic is stored in models, the controller glues things together, and the view builds the display. It's a formal and logical separation of logic and presentation.
One of the best, short, and simple books I have found on MVC is this one handed out last week at the PDC 2008 expo:
http://www.apress.com/book/view/1430216468
Not only does it cover MVC's concept, but its comparisons to other concepts such as Ruby on Rails and MVP methodology.
In addition, it goes into the entire reason MVC exists by describing it's seperation of concerns, and why it should not only be at the UI level - but down into your actual layers or IoC structure of your business objects and DAL.
I'd highly recommend this book as he covers best practices, in just 110 pages or so.
And no, I do not work for FirstPress or related to them at all. I just liked the book, and finally someone I agree with.
The best information I've found on doing widgets in ASP.NET MVC is on Steve Sanderson's blog. He explains his concept of partial requests which is a different technique than sub-controllers.
http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/
Partial Requests are easy You’ve heard of partial views, so how about
partial requests? Within any MVC
request, you can set up a collection
of internal partial requests, each of
which can set up its own internal
partial requests and so on. Each
partial request renders a plain old
action method in any of your plain
regular controllers, and each can
produce an independent widget. I’m
calling them partial “requests” rather
than “controllers” because they run a
proper MVC request-handling pipeline
that’s compatible with your routing
system and your controller factory.
Still, as with subcontrollers, all the
control remains in controllers, and
the view can be ignorant.
There are a lot of variations on the MVC theme and a lot to consider before coming to a conclusion as to the design of your particular system. Most of the latest, popular web based systems look to IoC as the guiding principal. Usually, some kind of framework component is the controller that uses some kind of configuration to invoke the proper template as the view and to couple it with the appropriate object hierarchy as the model. Most of these systems include an extensible GUI widget library to be used by the templates. You can add your own widgets but it is not best practice to hard code your widgets to a specific object hierarchy. That IoC link also talks about components and services which should give you some direction on how to avoid that hard coding.
ASP.NET MVC is well suited for a widget dashboard mashup type page.
Take a look at this session from PDC 2008.
You will probably want to use the Ajax helpers to update the islands of data in each widget. Here is a snippet of how you could put a calculator on any page but keep the code independent.
View Snippet:
<script type="text/javascript">
function OnFailure(error) {
alert("We have encounterd an error " + error);
}
</script>
<% using (Ajax.BeginForm("Add", new AjaxOptions{UpdateTargetId="sum", OnFailure="OnFailure"})){ %>
<%= Html.TextBox("x") %> +
<%= Html.TextBox("y") %> =
<span id="sum">?</span>
<input type="submit" value="AddEm" />
<% } %>
Controller Snippet:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(string x, string y)
{
int sum = int.Parse(x) + int.Parse(y);
return Content(sum.ToString());
}
I think JarrettV's and jcoby's answers are closest.
I've come to know subcontrollers as Hierarchical MCV (HMVC). The idea is that you "pull" content (a view populated by a subcontroller) from the parent view template instead of "pushing" data to the template from the controller. So instead of needing to edit both the controller and view to add a widget, you just call the widget from the view. There are libraries to accomplish this in the php frameworks CodeIgniter (Modular Extensions) and Kohana (Dispatch, and Component).

Resources