Should I use Databinding to put data on my web page? - asp.net

A video tutorial says I should use databinding to put data on my webpage. Is this the right thing to do?
It feels wrong to do it. Shouldn't there be a separation of concerns? The view should be separated from the code that connects to the database? In the aforementioned video, he connects to the database without going through a data access layer. What about the presenter/controller? It seems like we are completely bypassing those layers, going around the architecture.

It's important to realise that, when Microsoft produce a new UI technology, at least 2/3rds of it is designed to make it easy for newbies to slap together very simple 2-tier demo apps. I'm not saying this is a bad thing - after all, it helps us get up to speed on the technology quickly. However, when you are writing a proper n-tier app, then it's important to know which bits of the technology can and cannot be used.
For example, in ASP.NET WebForms, you should voluntarily restrict yourself as follows:
Don't use any data source control except for ObjectDataSource, and only use that for binding the Model to the View.
Don't use validation controls to validate input controls. Instead, pass all data to the Business Layer for validation and just display the resulting error messages on screen.
Don't use the built-in sorting/filtering/paging functions of the GridView. Instead, implement your own sorting/filtering/paging mechanism in the Business Layer.
To answer your original question: yes, data binding is very useful, as long as you bind to the Presentation Layer Model, rather than to a real data source.

Jonathan, you're thinking about ASP.NET MVC, whereas that tutorial is written for ASP.NET (which MVC developers like to refer to as ASP.NET Webforms). Have a look at the ASP.NET MVC tutorials here: http://www.asp.net/mvc/learn/
Keep in mind that although both have ASP.NET in the name, they're completely different programming philosophies. Webforms tries to mimic a stateful, event-driven form, like a Winform application. MVC, on the other hand, seperates it into models, views, and controllers, which fits very well with the web's stateless and request/response cycle.

Related

How does ObjectDataSource relate to traditional MVC pattern?

(Apologies for the vagueness of this question. It is the result of some muddy thinking on my part.)
I am designing a small website with an MSSQL DB. I have just stumbled across the ObjectDataSource class. I think I understand it, but I don't see how it relates to the traditional MVC design pattern, if at all.
The class, according to Microsoft, is designed to sit between the UI (View) and the database, and as such, I would think of it as a Controller. It does indeed map UI actions to behaviours, but it also contains code for writing to the database, which is not something I would expect a Controller to do (but I may be wrong).
It seems to me that it is both the Controller and the Model, but I get the feeling I am not seeing something here.
That's a lot of words to say I am very confused. I would be very grateful to anyone who can point me at anything that might help me to understand what I am missing here.
The purpose of the ObjectDataSource is to intermediate between the view and some code that retrieves your data, not to the database directly. It is not a controller, but something that would call your code to get the data. A better description would be from an MVP scenario, where in MVP the view can manage itself, and the ObjectDataSource is a control that makes that management easier. However, the ObjectDataSource may make it harder to work with a traditional MVP or MVC design implementation out of the box, depending on the framework setup.
I personally don't like this control; I never use it as I'd rather code it so it's easier to see how the binding takes place, in addition to when the binding takes place. My personal opinion.
ObjectDataSource is not used in asp.net MVC if that's what you mean "traditional MVC design pattern". It's used primarily in WebForms development.
It's usually dropped onto a webform component and configured via the UI, although it doesn't have to be. It provides an abstraction that allows other WebForms controls to interact with an object model in a manner that is similar to the way in which these controls work with Databases. This object model may ultimately come from a database, but it allows you to insert your own database methodology in between.
WebForms does not lend itself to the traditional MVC pattern due to some technical issues which complicate using it in that way. A cleaner pattern for use with WebForms is the MVP (Model View Presenter) pattern.

ASP.NET MVP pattern and implementation doubts

I am quite amused by the MVP Pattern http://webformsmvp.com/
How ever I have certain doubts on the implementation part.
Is it necessary that to use this pattern, I have to implement user controls?
I always thought that user controls are created if we need reuse of controls across pages.
Say if I want to implement and test MVP pattern,I should break my simple page with controls to a lot of user controls so that I can apply the MVP pattern?
What if I have quite a lot of standalone components in my webpage?
Is there any gap in my understanding of MVP?
Help.
It is not necessary to implement user controls to use this pattern, in short. Very briefly, you need a view (could be aspx or wpf or winform or console, etc.), a presenter that'll read from/listen to events from the view, make a call to the model and finally populate view with the right data, that's what MVP pattern is.
edit: this example is simple enough.
You don't have to use user control to use MVP pattern. MVP is GUI pattern that helps you to separate your concern.
For example, You write ASP.NET web page to calculate two numbers, with out MVP or MVC or any other GUI pattern, you would write all this logic in your code behind file which is very hard to test. If you want to test it, then you are bringing lot of extra baggages like ASP.NET framework.
In other hand, you write this app using MVP, you would do this.
View => Dumbest in all three. Doesnt have any or minimun logic. So you dont have to unit test it. It simply "tells" the presenter something happened and does what presenter asks.
Presenter => Controls the flow
Model => Business Logic/persistent logic.
I'm the author of the Web Forms MVP project you mention. This answer is specific to that library (which is just one implementation of the MVP pattern).
No, you do not need to use user controls. If you want, you can make your page inherit from MvpPage and it will then work with a presenter itself.
We recommend that you do use user controls though, even if you aren't using the control multiple times in your site. This lets you keep the view, view model and presenter logic nice and bundled as a logical unit for a particular feature. Pages are then used purely for laying out controls.

No viewstate or postback in ASP MVC?

I've been learning about MVC for a while, and I think I pretty much understand what it's all about. But there is one thing I don't yet understand: I keep hearing with MVC that there is no viewstate nor postback.
Can someone explain what this means in simple terms?
Try this SO answer which addresses the same question.
Extra info after comment/question:
ASP.Net web forms can use viewstate to store the state of server controls on the page and to manage invocation of server side events such as a button click. The idea is to present a programming model that is similar to the Win Forms approach to make it easier for Win Forms developers to transition and knock out browser based apps. To learn about it in depth you should hit google and learn about the asp.net page life cycle which will explain the overall process and explains where viewstate processing fits in. Here's a pretty good explanation.
ASP.Net MVC is a different programming model that uses different view engines to generate your markup - i.e. the content that actually streams back to your browser client. To an extent it removes a lot of the "magic" that web forms introduced but in return you can produce more standard markup and have greater control over what will be rendered to the client. If you're learning MVC take a look at the NerdDinner sample chapter which is a good tutorial as well as the MVC Music Store. Throughout those are good intros to doing MVC.
MVC doesn't use/need viewstate or postbacks as it's a different programming model. Which is better/more appropriate for any given project is a big debate that I'll let others have as I think both have their strengths and can be useful in different scenarios (although I personally mainly use MVC now...). You're right that things are done differently... you can't just work with the simple event driven approach that web forms imitates but then MVC has lots of strengths of its own which you'll find across countless blog posts comparing webforms vs MVC.
MVC Do not have viewstate and session but you can use TempData Object instead of viewstate.
in your controller you can bind like this TempDate["MyKey"]="My Value" and in the next request you can get your value in action like String s=TempData["MyKey"]

ASP .NET confusion - server controls

I have read through the information in this question: Controls versus standard HTML but am still rather confused.
The situation was I was asked to do a web project where I made a wizard. When I was done with the project everyone asked why I had used an <asp:Wizard...>. I thought this was what was being asked for, but apparently not, so after this I was led to believe that server controls were just prototyping tools.
However, the next project I did my DB queries through C# code-behind and loaded the results via html. I was then asked why I had not used a gridview and a dataset.
Does anyone have a list of pros and cons why they would choose to use specific html controls over specific server controls and why? I guess I'm looking for a list... what server controls are okay to use and why?
EDIT:
I guess this question is open ended, so I'll clarify a few more specific questions...
Is it okay to use very simple controls such as asp:Label or do these just end up wasting space? It seems like it would be difficult to access html in the code behind otherwise.
Are there a few controls that should just never be used?
Does anyone have a good resource that will show me pros and cons of each control?
Server Controls Rely on ViewState, Restrict Flexibility
Server controls were powerful tools to introduce WinForms developers to web development. The main benefit that Server Controls provide is a sense of statefullness and an event-driven development model. However, the state of web development has been maturing since the introduction of WebForms and server controls, which as a whole are being challenged with an increasingly critical view.
The main issue with Server Controls is that they try to abstract the behavior of the web too much, and in doing so, rely on ViewState data and server resources to perform their magic. ViewState data, when used excessively, can severely bloat the size of your page, resulting in performance problems.
Now it is possible to opt out of ViewState, but by then it probably is better to simply resort to regular HTML controls.
With HTML controls, you have precise control over the content of the web page and you have greater flexibility in what behaviors you want on your web page. Server controls offer limited client-side flexibility and force a lot of work to be performed on the server that can easily be performed in the browser with a good JavaScript framework.
Is it okay to use very simple controls such as asp:Label or do these
just end up wasting space? It seems
like it would be difficult to access
html in the code behind otherwise.
If you need to access the control in server side code, use a server control. If not, don't.
Are there a few controls that should just never be used?
Not in my (mid level) experience. The Wizard control, once you know how to use it, works as advertised (imagine coding all the features yourself, then do the math). I've used it and it resulted in a smooth and functional multi-page sign up form with intermediate saving of data.
Does anyone have a good resource that will show me pros and cons of
each control?
I do not, but I'd recommend using the right control for the right situation. Study the differences between a Repeater and a GridView, for example, and use the best choice for your needs.
There of course are alternatives. For one, MVC is gaining momentum. Personally I have not yet committed to learning it. As far as interactive forms and AJAX goes, many .NET devs opt to use JQuery for any validation and any AJAX (UpdatePanels being easy to use and horribly inefficient), with JSON as the transport mechanism to the server side.

What is the unit of reusability in .NET MVC apps?

In traditional ASP.NET Web Form applications, UserControls are a great way to encapsulate functionality so that it can be reused. However, UserControls don't fit well into the MVC model. They often make heavy use of ViewState and they blur the seperation of concerns that MVC promotes.
My question is, how do you best bundle a piece of functionality so it can be shared across MVC applications?
As an example, consider a from/to date-selector UserControl that:
allows a user to select two dates, either using a javascript overlay or by typing in day, month and year into seperate fields
can be configured to default to either today and tomorrow's dates or to dates of the developer's choosing
validates the dates that comes back from the user to ensure the from date is before the to date
exposes From and To properties that can be accessed by code-behind
How would I best build something like this in .NET MVC so that I can easily reuse it?
Note that to fully emulate User Control's functionality the MVC component would have to manage the submitted form data and validation - not just the presentation.
In general I would agree that user controls are nice in terms of encapsulating UI stuff, but I don't think too much has really changed in MVC. If I remember right re-using user controls across classic Asp.net projects was a pain and was never really the best way to truly create reusable components. Most UI toolkits that you bought for classic ASP.net didn't give you user controls, they gave you essentially server controls and javascript controls.
In your example, I would probably create or find a jquery (or ur framework of choice) plugin that did what you wanted on the client side. You could also build a C# wrapper around it similar to what Telerik did with some of the jquery UI controls. I do think that the word code-behind and even viewstate will disappear from your vocabulary the more you get into MVC.
If you look at what open source projects are out there for MVC you will get your answer in terms of what you should be doing.
The MVC Contrib app adds a lot of features by creating extension methods and helpers. Their grid control is a typical way to create a reusable component that you could use across projects
Telerik, created some extensions that wrap jquery controls and do asset management.
Finally I think if you look to the future, MVC has areas, which if I interpret it right will give you the ability to break your project apart into multiple smaller projects.
Besides what is already suggested, ASP.NET MVC v2 will have generic templated input controls, see here. You can read how other people do similar techniques, for example, here:
We have
exactly 1 method call for generating a
form element, “Html.InputFor”. As
part of that “InputFor”, it examines
an input specification, that collects
the PropertyInfo, any attributes, the
type, any modifiers called, and
selects an appropriate InputBuilder.
Call InputFor(p => p.Id) and Id is a
GUID? That creates a hidden input
element. Call InputFor(p =>
p.Customer.Address) and Address is a
complex type? That looks for a
partial with the same name of the type
Having considered the helpful answers from others, I will have a go at answering my own question.
It seems to me that the key difficulty with emulating UserControls in MVC is that they crosscut the concerns that MVC aims to seperate. The from/to date selector UserControl in my example incorporates elements of Model, View, Control and interation. UserControls' ability to bundle all this together is exactly the reason that they don't fit well into MVC.
That means that to create a psuedo-UserControl in MVC requires four seperate pieces:
A Model class - in this case an Interval class or similar
A PartialView that knows how to render the Model to HTML
A jQuery script to layer interactivity on top of the PartialView's HTML
A ModelBinder that can deserialise postdata into an instance of the Model class.
The ModelBinder is important because it deals with data coming back from the user. Without it, every Controller that wanted to display a to/from date selector in any of its Views would have to know how to assemble the six postdata fields - and how to cope if they were invalid or some were missing.
Two ways that I can think of. A partial view though this doesn't really transfer well from app to app because you are moving around ascx files. Not a big pain but not my flavour.
I prefer to use WebControls. They are super easy in mvc and all you need to do is reference the library in the project and possibly in your config file and there you go.
I think some of the answers have missed out on the postback functionality of controls. One way you could handle that is to pass any generic information via ViewData when rendering your partial view. That could then post back to its own control, which in turn could redirect to the UrlReferrer.
Its a little messy and use of UrlReferrer poses a security risk. But it is one way around the problem
You can create a jQuery plugin.
As user-controls provided in ASP.NET Webforms, MVC provide a lot of ways to make the controls and code that can be reused in other app.
Using Partials If your partial code have some C# logic and render the html using Razor/aspx code then it's bst to maintain them in razor file.
Write JavaScript Functionality as plugin If you maintain your code and write it as better as it can be used in other app then it would be a huge advantage for you. Next time when you work on other app just open this solution copy it and modify it. Write JavaScript code that can be used as plugin maybe take some more brainstorming.
Write Code As a Separate C# library If some code is too common for every app you make.for example you write a member authentication system or some global function (C#) that are used in every app you made then maintain them in a separate solution so it can be used in other app you made whenever you trying to make a new app in future.

Resources