Best practice HTML StringBuilder method (ASP.Net MVC) - asp.net-mvc

At first i have to say, i wanted to ask this question on programmers but i don't have enough reputation in this stackexchange.
While i was developing a ASP.Net MVC (4) Application i came to an issue where i had to display data from a model in a view where i need a recursive function which builds the HTML for me.
I asked myself where such a funtionality should be placed in best practices. The model should not hold any logic and the controller does not communicate with the view in common. And i really don't want to put complex logic into my view.
This is a theoretically question and i hope it is ok that i asked in this forum without giving source code.

You are quite right to keep your concerns separate. What you're looking for is a ViewModel.
What is ViewModel in MVC?

Related

Where best to POST changes made in an ASP.NET MVC non-form view?

I am fairly experienced with AngularJS and in the process of coming to terms with ASP.NET MVC while working with an existing application.
I am having trouble finding a satisfactory way to post changes to data in controls that are not in a webform. ASP.NET MVC has a clean and well documented mechanism for posting web form data, but the "right" way to get data from a view into a model with no submit event eludes me.
The code I am working with uses Ajax to achieve this, but I find it jarring to see a view requiring knowledge of communications protocols and addresses. To me this makes the object a hybrid between view and controller.
So where does such a call belong?
The View? Is my opinion expressed above wrong?
The Model? I don't think so. The model should not be concerned with how it is moved around IMO. It would become a model/controller.
The Controller? Seems the right place to me, but we have very strong positions against this expressed, for example, here: ASP.NET MVC: Access controller instance from view
I can't help feeling that there's a mechanism in ASP.NET MVC to POST non-webform values nearly as cleanly as webform values, but in the absence of such a beast I have to choose whether to place HTTP calls in either M, V or C.
I hope this isn't a stupid question.

Rails MVC concept in practice

I am not actually asking a question but rather an suggestion(or recommendation) on how to write code to fit nicely into Rails MVC pattern. Hope rails veteran or anyone familiar with MVC can give me some feedbacks.
I have an web app that talks to a RESTful api app via ActiveResource. It can fetch and update contents using API calls. It works perfectly. However, the web app does not have any models. The way it works is when user triggers an action(index,view,edit etc), the controller will directly call the REST api to fetch/update data.
My question is: Is it a good practice to do it this way or should I create models and populate data in there instead of directly calling the api? I was wondering if it is just a pragmatic compromise to MVC. I have just started working with Rails(and MVC) so I am open to any ideas, comments or recommendations on this
It's a bit of a catch-22 question. (I did wrote a huge answer but then deleted because it will be too tedious to read)
If you mean, can you implement the MVC pattern without a model, then the answer is no. The M means Model.
If they mean, can you use the MVC without using a model, then the answer is "yes", but it is no longer MVC, you have obliterated the the M i.e. Model.
I would recommend you to read MVC pattern in detail and then try to understand what your application actually trying to do.
http://c2.com/ is a very good place if you want to understand the design patterns.
A model is an object representing data or even activity, e.g. a
database table or even some plant-floor production-machine process.
A view is some form of visualization of the state of the model.
A controller offers facilities to change the state of the model.
Now in your case (it seems): you do have a data coming through via api so I would suggest populate the model properties and propagate it across.
Also Considering Pragmatic Compromise in MVC Dealing with things sensibly and realistically in a way that is based on practical rather than theoretical considerations. Omitting the use of Model in MVC do-not sound like a good idea, and it no longer remains MVC.
Having said that It seems from your point of view you are trying to say that Rails isn't necessarily strictly MVC hence why not use the way you want to :) but I will suggest to keep the integrity of MVC (and follow the purist approach).
http://c2.com/cgi/wiki?ModelViewController
Good read: jeff Atwoods: http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html (Feel free to skip the asp.net part)
https://stackoverflow.com/questions/1242908/in-english-what-really-is-model-view-controller
sums it all :) source is mentioned above.
"The model consists of application data and business rules" (wikipedia)
A model is essentially a table in your database locally.
If you're not storing any data, not validating any data, then you don't need a model.
If you want to clean up your code, maybe put some functions in a helper or in /lib

Model View Controller

Can someone help me understanding Model-View-Controller method to be implemented on WebForms? I am confused on couple of things:
If we have ABC.ASPX and ABC.CS files, what is view? is it only ABC.ASPX file? or combination of .ASPX + .CS file?
do we consider ABC.CS file as controller? If no, will it be a seperate class for controller?
Does database connection and data retreival go into Model or a seperate class which will be called by Model?
Can someone give a simple example for implementing Model-View-Controller in webforms?
Update
Hi guys, my question is how to implement Model-View-Controller methodology using WebForms not about ASP.NET MVC2.0. I apologise for the confusion.
Cheers
I guess I understood what you want to do: you want to implement a MVC architecture above an ASP.NET WebForms application. Fair enough.
All I can say is good luck! Me being there & done that. And how I regretted doing so... :P
Remember: ASP.NET WebForms is a huge abstraction, that tries to make the web into a statefull, event-based, windows-like environment, without any concern of decoupling whatsoever. So, trying to create an stateless, highly-decoupled and non-event-based architecture above that is, sorry to say, near insane.
Please, enlighten yourself and come to the real ASP.NET MVC world... :-)
PS: some people claim of having success implementing a MVP (Model-View-Presenter) architecture above ASP.NET WebForms. Shame on them (but you can try if you really want to)!
As others have posted there is a lot of information out there on MVC, so I'll answer your question...
If we have ABC.ASPX and ABC.CS files,
what is view? is it only ABC.ASPX
file? or combination of .ASPX + .CS
file?
It is both...however the .cs file is referenced as code behind but both make up the view.
do we consider ABC.CS file as
controller? If no, will it be a
seperate class for controller?
No, a separate class would be the controller.
Does database connection and data
retreival go into Model or a seperate
class which will be called by Model?
You could go either way. you could place this logic in the model, however you could also functionalize it out into services, which can then be called as needed by the model. IMHO the second route is the way to go, as I don't want to make my model dependent on external entities and it also makes testing the model easier, as you can separate out the services testing from the model testing.
Diagram can be seen here, which has some great imagery as reference points.

Using Code-Behind with ASP.NET MVC Views

Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.
Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.
I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.
Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).
Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.
I used code-behind extensively on my first ASP.NET MVC (Preview 3!) project - primarily for doing stuff like casting ViewData["foo"] into strongly-typed data objects, gathering view data into IEnumerables so I could loop across it, that kind of thing.
With the introduction of strongly-typed views, and pragmatic use of the (horrifically-named) Model-View-ViewModel pattern, I haven't missed code-behind at all since it was removed from the project framework just before the final release.
I now strongly feel that whatever processing you're doing in your view's code-behind, you are far better off modelling the result of that processing in your ViewModel, allowing the controller to perform the actual processing, and keep the view as simple and lightweight as you can. That'll let you test the processing logic, it makes the views easier to modify, and creates - I think - a much more elegant separation between transforming your data for display, and actually displaying it.
Yes the codebehind has long been the secret hiding place of business logic which as we all know should not be at the View level.
Code behind has been removed to stop naughty developers from being tempted.
I would recommend avoiding the codebehind in an MVC app at all costs. Using the code behind negates some of the values you get by using the MVC Framework such as separation of concerns, etc. You want to have your data access, business rules, type conversion and that sort of thing applied in the Model. If you find you need to convert your data types like Dylan mentioned, you may want to make ViewModels. The ViewModel would basically be the data from the actual Model you would like to display, in the format you wish to display it in.
Its probably best to avoid putting anything in the code behind when using MVC.
I would be interested to hear which part was being debated about, to go in the codebehind?
If you new to Asp.Net MVC, I really recommend spending some time going through the Nerd dinner example. There's a free EBook and source available here http://nerddinner.codeplex.com/.
Creating the simple demo from scratch is a great way to learn.
After doing this, it may shed some light on where the code you have in the codebehind, could alternatively go.
Note: If you do follow the EBook, grab the latest site.css file from codeplex, otherwise the virtual earth maps won't be aligned properly.
HTH
Ralph
It should be noted that "Code Behind" is a feature of the Web Forms view engine. It really has nothing to do with ASP.NET MVC itself.
For example, the Razor view engine in MVC3 does not even support it.
I would answer your question this way: If you cannot switch view engines without rewriting your controllers (or even your models) then you are not using the MVC pattern correctly.
Probably most of what you are doing in the .aspx.cs file should really be done before the model (or View Model) gets passed to the view. That said, in projects that I have migrated from ASP.NET Web Forms to ASP.NET MVC, I left a lot of the Code Behind in place. For example, I find it cleaner and more pleasing to use a Repeater control than to try to use a 'for' loop in Web Forms. I am still just iterating over View Model data after all. So why not? Separation of concerns is preserved (perhaps to a greater degree in fact).
I mean, why should "best practice" for Web Forms suddenly be the wrong way to do a Web Forms View? As a simple example, consider a Repeater that assigns a different CSS class to every second row of a table. Why should my controller (or even my model) care? Trying to put this kind of logic inline in Web Forms quickly devolves into tag soup and complete spaghetti. Now imagine something more complicated.
I have left Master pages in place that build the menus in the code behind. Again, all data comes from the View Model. I do not see why using GridView or other controls in this way should be a problem either.
I usually disabled ViewState in Web Forms anyway and did the data binding in "Init". Still, there would often be a small ViewState that I could not get rid of. I put some code in "Render" that moves this to after the form (it defaults to before). When moving to MVC, I sometimes left this code in. So, I have ASP.MVC sites that do indeed use Code Behind. I am just careful that it code that is specific to the view.
On new projects, I generally have found less of a need for Code Behind on most pages. Thankfully, view engines like Razor have made mixing code and mark-up in-line a lot less painful to write, read, and maintain.

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