ASP.NET MVC - Controller/Actions or Views or ViewModels first? - asp.net-mvc

I'm familiar with the various bits of functionality of the MVC plugin to create things. For example you can create a controller, write an Action method on it, then use the "create view" function in the context menu to create a view for it.
The question is, which is it recommended to do first?
I'm thinking I might start myself a methodology like this:
Plan out what the UI etc will look like and how it will work.
Write unit tests for the controller actions I think I might need.
Create Controller (maybe with default CRUD actions if it's to be that kind of controller).
Create ViewModel class for each controller action.
Create a strongly-typed view for each ViewModel.
Start building the view, working back through the ViewModel to the Controller as the View is built up.
What do you think of this approach, and what do you do?

Sounds like you're on the right track. Controllers are the most easily tested component of the three. Going controller-first will make it easier to follow Test-Driven Development practices.
I've not been perfectly happy with the default view templates, but every MVC guru will point you to T4 templates, which let you roll your own. They, like the out-of-the-box view templates, will be more effective with existing view models and controllers.

I'd be tempted to define the ViewModel first, the VM(s) can consist of all or a subset of the entities required for the various Views. How you segregate your VMs would depend on your app and how you are breaking up logical units within that.
Once I had the VM(s) in a basic form I would move to Model necessary for my chosen data store (unless I had an existing data store in which case I'd have started with the Model). Then onto the controllers. You can then apply TDD with a mocked data source to verify that the VM objects returned by the controller actions match expectations. Lastly, I'd generate basic strongly typed Views (based on the ViewModel objects) for each controller action that actually resulted in UI.
Then it's play time with Jquery and CSS to make it look presentable.

Related

what is the best way to bind ViewModel data to master page in asp.net-mvc

I want to dynamically create my menu on my master page and i have seen 2 different approaches:
First approach is have a base controller that loads up all shared view model data in its constructor. This is described here
Second approach is to create a separate controller for this and use this in your master page to inject specific view pieces into the master page without polluting your regular page view generation:
#Html.Action("Index", "Settings")
Is one better than the other? Is there any best practice here?
Personally I prefer the second approach as it allows to handle the menu independently from the main logic. By using child actions you could have an entirely separate lifecycle of the menu controller without the need to have a base view model for absolutely all views that use this masterpage. Inheritance just doesn't seem right for this situation but of course this doesn't mean that you should rule it out completely. Every scenario is specific and depending on the exact details (which you haven't provided for yours) there might different approaches.
Just don't think that if Html.Action is good for one scenario it will be good for all of them. There might be some project specific constraints which make inappropriate or maybe achieve this by some other approach.
There is no universal solution that will work in all situations. Otherwise there wouldn't be a need for programmers :-)

ASP MVC banner rotator

For my site I want to implement a banner control that will be on the left side of the site.
The banners will be stored in html in the database and each one will have a rating. Then using the rating each one will have a number of occurrences (percentage).
Do you think that there is a feasible solution to put all this flow in a separate dll? Is that even possible in the mvc architecture. I would prefer to do it as a partial view and have everything in a separate dll the partial view and the data access layer. Do you think that this is a good solution?
What is your approach when you have to implement a "user control" (partial view) ... do you put it in the website project or a separate project?
Is there any other way to implement this instead of using a partial view?
Thanks, Radu
There's a few choices that you have-
do it as a HtmlHelper extension. Probably not ideal for this kind of thing as the managementof the banners to display and the associated logic is really the concern of the banner component/widget/partial.
Do it as a partial view and use Html.RenderPartial(object Model) to call it. Now the logic is in the partial view, but there may also be some application logic that shouldn't really be going into the view and really belongs in the model or the controller. Also, you can end up with fat view models being passed to the main view that have to also carry a view model for each partial rendered in the main view. I think in some situations this isn't ideal, particularly when the data in the view models for the partials has nothing to do with the data for the main view. Which brings us to...
Do it as a child action with an associated controller and partial view. The logic will be nicely encapsulated in the controller and the partial view will simply render out whatever it's passed from the BannerController.
You could certainly put this in a separate assembly and set it up as a Portable area. This way, you can embed the partial views in the assembly and to reuse the widget would be a case of just dropping the assembly in the bin folder and referencing it in your main application project (you may also need to set up some configuration perhaps).
Whether I would personally do it this way or not depends on reuse for the component; to be honest, I'd probably set it up inside of an area in the main application to begin with and then, if I find that I need to reuse it, move it out to a portable area.
I also generally like to keep the data access logic in a separate assembly and use the repository pattern along with IoC to inject repositories for doing data access into controllers.

What is the proper structure for Asp.net MVC?

I read the Pro .Net Asp.net MCV book over the weekend and it provides some good examples on setting it up and using it. However my question is what is the structure of an MVC project should be. I ran into problems once I started trying to transfer control from one controller to another. It seems that you can have multiple views within one controller. Also when you execute the Redirect("Action", "Controller") command it seems that the routing wants to look for the view within a sub of that controller. So my questions are:
Is there rule of thumb of 1 controller to 1 view?
Should you call another controller from a controller?
What is the proper way to transfer control from one controller to another?
You can have as many views/partial views per controller. The rule of thumb as far as one can deduce it from the MVC samples is, that a controller encapsulates a set of functionality that belongs together, e.g. listing products and creating, updating, deleting as single product.
You can use Html.ActionLink to route from one view to another. To call one controller from another, IMHO, makes only sense for partial views - however that depends on the problem.
Html.ActionLink or Html.RouteLink.

ASP .NET MVC correct UserControl architecture

I'm trying to learn the new ASP .NET MVC framework and would like to know the best practice for using UserControls.
I understand that you can render UserControl's as a partial and pass data to them from a controller. Ideally I would think that it makes sense not to have a code behind file as this creates a temptation to break the MVC rules.
I'll give an example where I don't understand how UserControls fit into the pattern.
I have a UserControl that shows the
latest tags (much like on
StackOverflow). Unlike StackOverflow I
want to display this UserControl on
all of my pages. If I have a
controller say QuestionController
which is meant to handle actions from
some question views e.g. view and
detail, does this mean I have to fetch
the data in the QuestionController and
then pass it to the UserControl?
If I create another controller say
SearchController then I would have to
replicate the same functionality to
get the latest tags to pass to a
partial again. Doesn't this mean that
the 2 different controllers are doing
extra things that they weren't
originally intended to do?
If your UserControl appears on every page, then one way to address this would be to use a base controller from which all of your controllers derive and generate the ViewData for the UserControl by overriding the OnActionExecuting method and putting the logic there. If your UserControl is less pervasive, but still frequently used throughout the site, you could extend ActionFilterAttribute and have your filter generate the needed data. This attribute could be used to decorate the controllers or actions that generate views that use the UserControl.
I'm assuming in all of this that the data for the UserControl is independent of the action being invoked. If there is a dependency, it's probably best to push the logic into a class (or classes, perhaps using Strategy) and make the generation of the data explicit in each action or controller (via overriding OnActionExecuting).
Alternatively, with ASP.NET MVC 2 you can now use RenderAction to call a completely new controller action which can fetch the data. This makes your code much more modular and it is more clear where the data is coming from.
You can also consider putting your model classes in an hierarchy. The upper class (or one of the upper classes) will contain data necessary for your pervasive user controls. Then you can load these commonly used data in a base controller class.

Code behind in ASP.NET MVC

What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?
Here's my list of reasons why code-behind can be useful taken from my own post. I'm sure there are many more.
Databinding legacy ASP.NET controls - if an alternative is not available or a temporary solution is needed.
View logic that requires recursion to create some kind of nested or hierarchical HTML.
View logic that uses temporary variables. I refuse to define local variables in my tag soup! I'd want them as properties on the view class at the very least.
Logic that is specific only to one view or model and does not belong to an HtmlHelper. As a side note I don't think an HtmlHelper should know about any 'Model' classes. Its fine if it knows about the classes defined inside a model (such as IEnumerable, but I dont think for instance you should ever have an HtmlHelper that takes a ProductModel.
HtmlHelper methods end up becoming visible from ALL your views when you type Html+dot and i really want to minimize this list as much as possible.
What if I want to write code that uses HtmlGenericControl and other classes in that namespace to generate my HTML in an object oriented way (or I have existing code that does that that I want to port).
What if I'm planning on using a different view engine in future. I might want to keep some of the logic aside from the tag soup to make it easier to reuse later.
What if I want to be able to rename my Model classes and have it automatically refactor my view without having to go to the view.aspx and change the class name.
What if I'm coordinating with an HTML designer who I don't trust to not mess up the 'tag soup' and want to write anythin beyond very basic looping in the .aspx.cs file.
If you want to sort the data based upon the view's default sort option. I really dont think the controller should be sorting data for you if you have multiple sorting options accessible only from the view.
You actually want to debug the view logic in code that actuallky looks like .cs and not HTML.
You want to write code that may be factored out later and reused elsewhere - you're just not sure yet.
You want to prototype what may become a new HtmlHelper but you haven't yet decided whether its generic enough or not to warrant creating an HtmlHelper. (basically same as previous point)
You want to create a helper method to render a partial view, but need to create a model for it by plucking data out of the main page's view and creating a model for the partial control which is based on the current loop iteration.
You believe that programming complex logic IN A SINGLE FUNCTION is an out of date and unmaintainable practice.
You did it before RC1 and didn't run into any problems !!
Yes! Some views should not need codebehind at all.
Yes! It sucks to get a stupid .designer file created in addition to .cs file.
Yes! Its kind of annoying to get those little + signs next to each view.
BUT - It's really not that hard to NOT put data access logic in the code-behind.
They are most certainly NOT evil.
Ultimately, the question you ask yourself is this:
Does this code A) Process, store, retrieve, perform operations on or analyze the data, or B) Help to display the data?
If the answer is A, it belongs in your controller. If the answer is B, then it belongs in the view.
If B, it ultimately becomes a question of style. If you have some rather long conditional operations for trying to figure out if you display something to the user, then you might hide those conditional operations in the code behind in a Property. Otherwise, it seems like most people drop the code in-line to the front end using the <% %> and <%= %> tags.
Originally, I put all my display logic inside the <% %> tags. But recently I've taken to putting anything messy (such as a lengthy conditional) in my code behind to keep my XHML clean. The trick here is discipline - it's all too tempting to start writing business logic in the code behind, which is exactly what you should not be doing in MVC.
If you're trying to move from traditional ASP.NET to ASP.NET MVC, you might aviod the code behinds until you have a feel for the practices (though it still doesn't stop you from putting business logic inside the <% %>.
There isn't a purpose. Just don't use it except for setting the model
ViewPage<Model>
See this blogpost for more info.
At this Blogpost is a working example of removing the code behind.
The only problem I'm stuck with is that it is not able to set namespaces on the class.
The codebehind provides some of the strong typing as well as the intellisense support that you get in the view. If you don't care about any of these two features, you can remove it.
For example, I typically use the NVelocity ViewEngine because it's clean and pretty straight forward.
This is a great question. Doesn't MVC exist in the ASP.NET environment, without using the specific MVC pattern.
View = aspx
Controller = aspx.cs (codebehind)
Model = POCO (Plain Old C#/VB/.NET objects)
I'm wondering why the added functionality of MVC framework is helpful. I worked significantly with Java nd MVC and Java Struts several years ago (2001), and found the concepts in MVC to be a solution for the Internet Application organization and development problems at that time, but then found that the codebehind simplified the controller concept and was quicker to develop and communicate to others. I am sure others disagree with me, and I am open to other ideas. The biggest value I see to MVC is the front controller pattern for Internet development, single entry source for Internet Application. But, on the other hand, that pattern is fairly simple to implement with current ASP.NET technologies. I have heard others say that Unit Testing is the reasoning. I can understand that also, we used JUnit with our MVC framework in 2001; but I have not been convinced that it simplifies testing to use te MVC framework.
Thanks for reading!

Resources