Where does formatting logic belong with MVC? - c#

Say my phone number is stored in the database as a 10-digit string:
0000000000
And I want to format this phone number when presenting it to the user as:
(000) 000-0000
And I have an extension method in a utility assembly that handles this formatting:
static string ToPhoneNumber(this string value)
{
return Regex.Replace(value, #"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
}
My question is, at what point do I apply this conversion?
1) In the view:
#Model.PhoneNumber.ToPhoneNumber()
2) In the view model:
public string FormattedPhoneNumber
{
get
{
return this.PhoneNumber.ToPhoneNumber()
}
}
3) In the controller:
userModel.FormattedPhoneNumber = userModel.PhoneNumber.ToPhoneNumber()
4) In the domain model (same implementation as #2)
5) In the service (same implementation as #3)
Also, does the answer depend whether it's a global formatting need (like phone number) vs. an isolated one-time formatting on a single view?
I would give my thoughts, but don't want to influence any answers.

I personally like to keep things in my ViewModel because what you end up with is strange looking code in your view if you don't. Let's take your example.
Razor View:
#using MyNamespace.Models.Extensions
#model MyNamespace.Models.ViewModels.IndexViewModel
#if (string.IsNullOrWhiteSpace(Model.PhoneNumber) {
<div> #Model.PhoneNumber.ToPhoneNumber() </div>
}
Versus the alternative:
Razor View:
#model MyNamespace.Models.ViewModels.IndexViewModel
#Model.FormattedPhoneNumber
ViewModel :
public string FormattedPhoneNumber {
get {
return PhoneNumber.IsEmpty()
? "Not Available"
: PhoneNumber.ToPhoneNumber();
}
}
You could definitely improve my code, but the point is that it keeps your views simpler and lest cluttered with branching logic.
Also, I never claimed to be a saint, so I don't always follow my own advice, but I should. Do as I say, not as I do :)

I think it is view responsibility to decide how to display data. Because only the view knows what is available for presentation. On the other hand it is probably easier to do it in controller. And controller would know about locale of the user. Over all I think it makes very little difference.

First off, with architectural patterns in general, and especially those dealing with "separation of concerns", the final arbiter is always "what is the best approach in my scenario" - I strongly believe that dogmatic adherence to a set of rules without considering your own plans and needs is a horrible practice. Not to mention the fact there is no clear consensus here: depending on your variety of XYZ (MVC, MVP, MVVM) you'll find opposing thoughts on what goes where all over the internets.
That said, my quick-twitch answer to the question is "Use your judgement".
Arguments for "in the view":
it deals with presentation, therefore it is the views responsibility
Arguments for "in the view model":
generally, the role of the view model is to provide "ready to data bind" representations of the model - hence, transforming model data into a form directly consumable by the view is the responsibility of the view model
Arguments for the model:
this could be an excessively common representation for the model data; therefore, following DRY, the model will assume responsibility for this representation
Arguments for the controller:
... Ok, can't think of a reasonable one here. Controllers typically respond to actions, so it's a stretch to justify it belonging here.
The point I'm trying to make is that so long as a single point of your system accepts and takes on the responsibility and that responsibility is handled solely by that component/layer/class, you've accomplished the primary goal, which is to prevent dilution/repetition/low cohesion.
My personal opinion, fwiw, would probably fall on the view or view model. If this were WPF I'd almost certainly say the view (via the format providers available to wpf data binding). In the web world, I'd probably lean towards the view, although a strong argument for the model exists - say you now want to expose this data via a REST/JSON/etc service: you can easily handle this change (assuming you want to return the formatted data, that is)
TL/DR: It really depends; follow common sense and use your judgement. Just keeping all the related logic in a single place is the important part, and question any dogmatic/commandment-style "Thou Shalt" statements.

It depends on a few things your definition of ViewModel, are you following a (self-coined) MVCVM* approach, where you'd have a ViewModel specific to your view in addition to your domain models?
If so, the VM could certainly contain the formatting logic, that is the whole point of having this View Model in the first place, to Model the View. So Option 2.
That said, the reasoning behind this is that formatting yourself would begin to the DRY principle if you were formatting like this:
#Regex.Replace(Model.PhoneNumber, #"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
Since you've got an extension method, it's not that much of a problem to call the formatter in your view at all, but I'd still prefer to do it in the dedicated VM.
If your VM is really just the domain model that contains the raw data (see this, pattern 1) then it should definitely be in your View, so Option 1. Just a note, that if you're using this pattern I'd suggest against it as it's making your view strongly coupled against a low-level object, you're better abstracting this out into what you need ensuring that your couplings between Domain Model + View Model are actually strong (ie. compiled at compile time, not runtime!).
Above all - This should certainly not go into your domain model.
* Model, View, Controller, ViewModel. Where the ViewModel contains the data that is to be consumed in your View, in the format of which it requires.

I would place this in the viewmodel and not in the view. The view is intended to just present the data/information to the end-user. Keeping up the separation of concerns makes sure every object is as independent as possible. If you pass the formatted numbers to the view, the view has no concerns about what is to be displayed, just display the formatted numbers.

I would argue that this is modeling, not formatting. If the receiving application needs to re-format the order, spacing or capitalization of these fields it must first split the single field into several separate fields.
This should be the responsibility of the Services layer. We are talking schema, not format. The application requires that the fields be split as part of its data contract. Where this split happens should be in the Application Services layer that your app consumes.
The services layer should try to add metadata to the information through schema.
For example, if I receive a phone number from a data contract like this:
1234567890
The requriements for presentation are as follows:
(123) 456 – 7890
The services tier should be breaking the phone number apart into its elements
<PhoneNumber>
<CountryCode>1</CountryCode>
<Area>123</Area>
<Prefix>456</Prefix>
<LineNumber>7890</LineNumber>
</PhoneNumber>

Option 1 is the best, followed by 2.
In the controller, you should actually remove the formatting to send it to the service layer, so neither the domain model nor the service model are aware of the formatting.

Related

MVVM Calculated Fields in Model or ViewModel?

I am trying to determine the correct pattern for handling Calculated fields or methods in MVVM. I have a number of calculated fields that will be required for both the presentation layer and some back end processing. Let say it is "CalculateTotal" which is based on summing a number of different values from the Data object and its sub objects.
I would like this calculation in one location. The first thought is that it belongs in the model (i.e., not the viewModel) since the model object will be passed to other back end processing systems. What is then the best way to make this available to the ViewModel?
Option 1, is that I statically load the viewModel when I create it based off the Model (e.g., vwModel.Total = model.CalculateTotal())
This suffers if I am needing to update the ViewModel dynamcally, for example I modify the underlying data and try to get the new total.
Option 2: More service oriented and each calculation calls a service to return the values. The issue I see with this is more performance based. Once I load my object once, I have all the data needed to perform the calculation. It seems each call would require the data object to be reloaded
Option 3: Have the ViewModel contain the data model and create methods to call the data model methods
Thoughts? Suggestions?
I would do all calculations in the model. The view model should subscribe to events (e.g. via INotifyPropertyChanged) on the model, so when the back-end values change, the view model will be notified.
The view model can, of course, interrogate the model for calculations and doesn't have to get all information through events. The above is only for when the data changes come directly from the model or the underlying data layer.
I would go with something like option 2. Moving the calculation logic out of the model and view model will simplify things and make that logic more reusable by other classes. From your question it seems like you already have an idea of how to implement that. Keeping the model "dumb" and having services/utility/helper classes that know how to process the model will help you in the long run if the model is being passed around a lot. Just something to think about but keeping the responsibility of a class very limited makes for easier code maintenance down the road. You might end up with more classes but I personally find it easier to focus and work on two or three small classes than one very large class. I don't know what type of application you have or how heavy the calculations are but unless you are having measurable performance issues I wouldn't worry about trying to pre-optimize things.
I would like this calculation in one location.
If there is a dedicated Service Layer, then almost all calculations should be done in Service Layer.
Option 1
Instead of using CalculateTotal method on Model, it's better make a read only property Total and calculate it in a service layer method every time Model is requested. This is the easiest and the best option to use if there are no performance issues, since it drastically simplifies ViewModel.
Option 2
Calling a dedicated CalculateTotal service method from ViewModel is the only option available if calculation process is resource intensive and calculated total is not used every time Model is requested.

Correcting user input in ASP.NET MVC4

Background
We've been migrating a large amount of legacy code & systems to ASP.NET MVC forms. I've already coded up a number of CRUD type interfaces with MVC 4, using model binding, validation, attributes etc., so I'm fairly familiar with that whole paradigm. So far, all of these forms have been on our backend administration & management applications, where it pays to have very strict input validation. We are launching our first consumer facing application in MVC and are faced with a different type of problem.
The Problem
Our legacy forms in this area are the main revenue engine for our company. Usability of the consumer experience is the rule of the day. To that end, we want our forms to be as lenient as possible - the legacy system did a number of things to automatically correct user input (in entirely custom, non standard ways each time, of course). To that end, we don't so much want input validation as we want sanitation.
Examples
We ask the user for numerical inputs which have a unit of measure implied. Common ones are currency amounts or square footage. The input label is clear that they don't need to provide these formats:
What is the approximate square footage? (example: 2000)
What is your budget? (example: 150)
People being people, not everyone follows the directions, and we frequently get answers like:
approx 2100
1500 sq. ft.
$47.50, give or take
(Okay, I exaggerate on the last one.) The model that we are ultimately storing into our business logic accepts numeric input type for these fields (e.g. int & float). We can of course use datatype validator attributes (example [DataType(DataType.Currency)] for the budget input, or just having the field type be an integer for the square footage) to clearly indicate to the user they are doing it wrong, providing helpful error messages such as:
The square footage must be numbers only.
A better user experience, however, would be to attempt to interpret their response as leniently as possible, so they may complete the form with as little interruption as possible. (Note we have an extensive customer service side who can sort out mistakes on our system afterwards, but we have to get the user to complete the form before we can make contact.) For the square footage examples above, that would just mean stripping out non-digit characters. For the budget, it would mean stripping out everything that's not a digit or a decimal point. Only then would we apply the rest of the validation (is a number, greater than 0, less than 50000 etc.)
We're stuck on the best approach to take to accomplish this.
Potential Solutions
We've considered custom attributes, custom model bindings, and a separate scrubber service class that would live between the model and the database. Here are some of the considerations we've taken into account trying to decide upon the approach.
Custom Validation Attributes
I've read a number of helpful resources on this. (They have varying degrees of relevancy and recency. A lot of stuff I found searching for this was written for MVC2 or MVC3 and is available with standard attributes in MVC4.)
Extending ASP.NET MVC’s Validation
Custom Validation Attribute in ASP.NET MVC3
A lot of questions & topics on input sanitization which were focused on Cross-site scripting attacks or database injection.
What I haven't found is anyone doing what I want to do, which would be changing the model value itself. I could obviously create a local copy of the value, sanitize it and provide a pass/fail, but this would result in a lot of duplicate code. I would still have to sanitize any input values again before saving to the database.
Changing the model value itself has 3 benefits:
It affects subsequent validation rules, which would improve their acceptance rate.
The value is closer to what will be put into the database, reducing the additional prep & mapping overhead needed before storage.
In the event of the form being rejected for another reason, it gently suggests to the user "You're trying to hard on these fields."
Is this a valid approach? Is there someone out there who has used validation attributes in this way that I just missed?
Custom Model Binding
I read Splitting DateTime - Unit Testing ASP.NET MVC Custom Model Binders which focuses on custom date time input fields with custom validation & parsing done at the model binding layer. This lives a lot closer to the model itself, so it seems like a more appropriate place to be modifying the model values. In fact, the example class DateAndTimeModelBinder : IModelBinder does exactly that in a few places.
However, the controller action signature provided for this example does not make use of an overall model class. It looks like this
public ActionResult Edit(int id,
[DateAndTime("year", "mo", "day", "hh","mm","secondsorhwatever")]
DateTime foo) {
Rather than this
public ActionResult Edit(
MyModelWithADateTimeProperty model) {
Shortly before that, the article does say
First, usage. You can either put this Custom Model Binder in charge of all your DateTimes by registering it in the Global.asax:
ModelBinders.Binders[typeof(DateTime)] =
new DateAndTimeModelBinder() { Date = "Date", Time = "Time" };
Would that be sufficient to invoke the model binding for the date time field on the single-parameter model example MyModelWithADateTimeProperty?
The other potential draw back that I see here is that the model binder operates on a type, rather than an attribute you can apply to the standard data types. So for example, each set of validation rules I wanted to apply would necessitate a new, custom type. This isn't necessarily bad, but it could get messy and cause a lot of repeated code. Imagine:
public class MyDataModel {
[Required]
public CurrencyType BudgetRange { get; set; }
public PositiveOnlyCurrencyType PaymentAmount { get; set; }
[Required]
public StripNonDigitsIntegerType SquareFootage { get; set; }
Not the ugliest model code I've ever seen, but not the prettiest either.
Custom, External scrubber class
This has the fewest questions for me, but it has the most drawbacks as well. I've done a few things like this before, only to really regret it for one of the following reasons:
Being separate from the controller and model, it is nigh impossible to elegantly extend its validation rules to the client side.
It thoroughly obfuscates what is and what isn't an acceptable input for the different model fields.
It creates some very cumbersome hoops for displaying errors back to the user. You have to pass in your model state to the scrubber service, which makes your scrubber service uniquely tied to the MVC framework. OR you have to make your scrubber service capable of returning errors in a format that the controller can digest, which is rather more logic than is usually recommended for a controller.
The Question
Which approach would you take (or, have you taken) to accomplish this type of sanitization? What problems did it solve for you? What problems did you run into?
I would take ModelBinder approach.
When form data comes in - it goes to model binders infrastructure. There you can override decimal model binder to refine input. After that you can send it to validation routines without neeed to write specific validation attributes or something like that.
Also you can use one intelligent model binder that will do type switch internaly or override ModelBinderProvider, so your code wont be bloated with ModelBinderAttribute. Here is Jimmy Bogart article about this. Also you will get some flexibility, because you can use attributes to declare if model uses strict or adaptive binding.
In overall, IMHO, validation attributes are not suposed to alter input. They should validate it. Model binders are in fact responsible for converting all weird stuff that comes in into something usable in your system and your third approach duplicates Model binder functionality)
Hope this helps and sorry for my english)

MVP: Passive View (with EF) and layers

I'm creating an application using MVP: Passive View and EF (model first). As of know, I have a presenter getting data directly from the DataContext created through EF. It looks something like this:
private void UpdateOrderTableControl()
{
IList<Order> orders = dataContext.Orders.ToList();
IList<OrderViewModel> viewOrders = new List<OrderViewModel>();
foreach (var o in orders)
{
viewOrders.Add(new OrderViewModel()
{
OrderId = o.Id,
CustomerId = o.CustomerId,
LastName = o.Address.LastName,
FirstName = o.Address.FirstName,
Company = o.Address.Company,
Weight = o.Weight,
Sum = o.Sum,
Date = o.Date
});
}
view.GetOrderDataGridView().DataSource = viewOrders;
}
So the presenter gets a list of all orders, creates a list of order view models (combining data from different tables, i.e address above) and then sends the view model list to the view.
It's pretty much the same thing the other way around, when retrieving data from the view in order to edit or add to the db:
private void SaveOrder()
{
GetOrderDataFromView();
if (isNewOrder)
{
dataContext.Orders.Add(selectedOrder);
}
else
{
dataContext.Entry(selectedOrder).State = EntityState.Modified;
}
dataContext.SaveChanges();
isSaved = true;
UpdateOrderTableControl();
}
1) Can EF (the entities created through EF, the DataContext etc) be considered as the DAL? Should it be in a project of its own?
2) I guess the presenter should not have access to the DataContext like that, but rather to another layer in between the two, right? Would that be a service layer, a business layer or both?
3) Is what I refer to as a view model in fact a view model or is it something else? I just want to get my terminology right.
EDIT:
4) I read some suggestions about adding business logic to the entities generated by EF, but that doesn't sound quite right to me. Should I create business objects in a separate business layer on top of EF? Meaning I would have Order (generated by EF), OrderBO (the business object) and OrderViewModel (the order to be displayed). I would have to do more mapping, since I'd add another layer, but it would make the presenter lighter.
Thanks in advance!
Nice questions!
Well, the answer to all of them depeneds on what you plan to do. The first you have to do is to evaluate if the effort needed to implement each pattern is worth the pain.
1)Are you going to switch between different implementations of forms and/or have massive unit tests for the UI alone? Then yes passive view seems a good idea.
2)Is it not so much pain to have a litle code inside the forms? Then MVP supervising controller can be faster to implement.
3)Can most of the logic of your program be inside bussiness layer? After you have all the logic inside BL, how much logic is GUI specific? If it is not that much then code inside the forms with no GUI patterns is the way to go.
About the questions:
1) Yes, EF can be considered a DAL, and doesn't hurt to be in a different project. Since you are into patterns, a usefull pattern here is Repository and Unit of Work Pattern that abstracts EF and lets you unit test the BL. (test without accessing an actual database, with a fake DAL implementation)
2) Depends. EF objects can be considered Data Transfer Objects since they are POCO. DTOs are visible in all layers. Another strategy is to have layer specific objects, mainly in the scenario of a tiered application (each layer in different machine).
If not forced to do otherwise, I would have EF objects visible to all layers but the DataContext itself visible only to BL, not GUI layer. This means that queries and transactions are done in BL but GUI can get the results in the same format.
3) If you follow the above advice, this rather bad object copying isn't needed.
4) This strategy you refer to is the Domain Model (google for more), in which you put logic inside the domain objects, that can also access the database. Again if you follow the advice in 2), this doesn't bother you.
Before getting frustrated around patterns and their correct implementations though, really focus on your needs! The goals are fast delivery and easy maintainance. Too much abstraction can hurt both!
Regarding the question #2, it will be better to differentiate and make some abstractions on Data Access Layer. If you continue keep it inside Presenters, that means your client will ask database each time, load some data and then make some calculations.
If you are working on Client-Server application, it will be better to not mix-up the server logic and client logic. Presenters are definitely on client side, DAL on server-side. You can connect client to server with web services (ex. asmx, wcf).
I see at least three huge reasons to do this:
Ability to write simple unit tests on your presenter without real back-end and server logic
Scale your server side if needed.
You will be able to send less data to client if you make some required calculations on server side
Regarding #3, with passive-view pattern, there is a Presenter, which requesting data (sometimes it called Model), prepare it to display and send to View to render. In Model-View-ViewModel pattern, ViewModel will send request to server and prepare data to display. The difference between MVVM and PassiveView how Presenters and ViewModels are working with View. In PassiveView Presenter will know about View's interface to be able to send data to render. In MVVM View knows about ViewModel and bind data from ViewModel.
The last one, #1. I think yes, it is some Infrastructure layer. If you make an abstraction here, you will be able to move some optimization commands, set loading options (EF is very flexible here) and you will be able to do it quickly.

Why don't use repository in the view

I have a partial view that loops through its Model (a list of things) to show the thing.Name and three integer values that are counts of related entities.
First of all, I tried putting: (pseudo-razor)
foreach(thing in Model){
#thing.Name :
#thing.related.entities.where(condition1).Count()
#thing.related.entities.where(condition2).Count()
#thing.related.entities.where(condition3).Count()
}
But its really slow... so I created a function in the ThingRepository that does same queries faster, something like this (pseudo-code)
function GetCountofRelatedEntities(relatedID,condition){
return db.entities.where(relatedID==relatedID && condition).count()
}
and its much faster, so I want to call it. I think I should call it from the controller, but then I need a ViewModel to keep a (thing, int, int, int) collection as the model, or I can use the ViewBag extremely to pass the results to the view, but, and here is the question:
Why not simply use the repository from the view? whats wrong with this code in the view? (pseudo-razor)
#repo=new ThingRepository()
foreach(thing in Model){
#thing.Name :
#repo.GetCountofRelatedEntities(thing.relatedID,condition1)
#repo.GetCountofRelatedEntities(thing.relatedID,condition1)
#repo.GetCountofRelatedEntities(thing.relatedID,condition1)
}
Could you tell me why I shouldn't instantiate the repository inside a View? Or I can do it?
Why not simply use the repository from the view?
Because you are violating the MVC design pattern. A view's responsibility is not to fetch data. It is to display data that it is being passed to it from the controller under the form a view model. And it's as simple as that.
You could call repositories or whatever you like in your views but just don't tag your questions with asp.net-mvc anymore because you are no longer doing any MVC. I mean you could do whatever you like - you could even write SQL queries in your view if you want.
But the whole point of the MVC design pattern is to separate the data retrieval logic from the presentation logic.
One purpose of the MVC pattern is to provide a structure that fits a wide range of common programming situations. To simplify:
Model: Describes the shape of your application, i.e. the parts of your software specific to your business.
View: Display the data to the user and transmit user events to the server.
Controller: Acts as a middleman between the view and the model.
What you're proposing "works," in the sense that it gets the data on the page where you want it. In the short term, it appears to be saving you time and effort, as you don't have to bother with controllers, viewbags, etc.
However, you are breaking the MVC structure in a way that you will probably regret later on. For example, say in a few weeks your boss comes to you and says, "Hey, you know that page you added to display that list of entities? We need to do some filtering and sorting on it. And I need it yesterday."
Now you're faced with a choice: Do I add this filtering logic to my view page and meet the deadline, or do I take the time to move the data access code to a controller and rework my view, at the risk of missing the deadline and breaking what's already working?
You'll probably take the easy way out and add the logic to the view, and now you've got a growing mess on your hands. We've been down this road with VB6 and Webforms apps with 6,000-line codebehind files. Trust me--you don't want to go there.
Another problem is that the MVC structure is well understood by the programming community. If someone else comes along and tries to work on your code, you're making it harder for them by deviating from the conventional approach.
The MVC structure is time tested and sound. Until you fully understand its purpose and the benefits it provides, try to follow it closely. It's not a good idea to break the rules until you have a firm grasp on them.
My main objection would be the separation of concerns. Once you start hitting your DB from your view, your "view" really isn't just a view anymore. It's really handy to have a clean separation between your data access and your view.
Why is this separation of concerns important? It makes it easier to work with systems that are composed with these clean separations. When you need to adjust what data is retrieved, you'll never need to fuss with the view. So long as the view gets the right value, it will display it correctly. Likewise, if you want to change how values are displayed, you can modify the view without any chance of borking the data.
The thing is that you should not have any logic in your View because this is not the MVC approach.
MVC is Seperation of concern.
So you should create your ViewModel wich contains ALL the data your View needs.

validations in MVC / MVP

I'm new to MVC / MVP and learning it by creating a Winform application.
I have to some extent created the Models, Presenters and Views... Now where do my validations fit.
I think the initial datatype validation (like only numbers in Age field), should be done by view. Whereas the other validations (like whether age is within 200) should be done by model.
Regarding datatype validation, my view exposes the values as properties
public int? Age
{
get
{
int val;
if (Int32.TryParse(TbxAge.Text, out val))
{
return val;
}
return null;
}
set
{
TbxAge.Text = value;
}
}
I can perform validation seperately, but how do I inform presenter that validation is still pending, when it tries to access the property Age ?. Particularly when the field is optional.
Is it good to throw a validationpending exception, but then the presenter must catch it at every point.
Is my understanding correct, or am I missing something.
Update (for the sake of clarity) : In this simple case where the age field is optional, What should I do when the user typed his name instead of a number. I cant pass null as that would mean the field has been left empty by the user. So how do I inform the presenter that an invalid data has been entered...
Coming from the MVP side (I believe it's more appropriate for WinForms) the answer to your question is debatable. However the key for my understanding was that at anytime you should be able to change your view. That is, I should be able to provide a new WinForms view to display your application or hook it upto a ASP.NET MVC frontend.
Once you realise this, the validation becomes aparant. The application itself (the business logic) should throw exceptions, handle errors and so forth. The UI logic should be dumb. In other words, for a WinForms view you should ensure the field is not empty, or so forth. A lot of the properties for the controls allow this - the properties panel of Visual Studio. Coding validation in the GUI for the likes of throwing exceptions is a big no no. If you were to have validation on both the view and the model you'd be duplicating code - all you require is some simple validation such as controls not being empty for example. Let the actual application itself perform the actual validation.
Imagine if I switched your view to a ASP.NET MVC front end. I would not have said controls, and thus some form of client side scripting would be required. The point I'm making is that the only code you should need to write is for the views - that is do not try to generalise the UI validation across views as it will defeat the purpose of separating your concerns.
Your core application should have all your logic within it. The specalised view logic (WinForms properties, Javascript etc...) should be unique per view. Having properties and interfaces that each view must validate against is wrong in my opinion.
If your "view exposes the values as properties", I suspect that you are missing something. The principal distinction between MVP/MVC and some of the other UI decoupling patterns is that they include a model, which is intended to be the main container for data shared by the view and presenter or controller.
If you are using the model as a data container, the responsibility for validation becomes quite clear. Since only the presenter (or controller) actually does anything besides display the data, it is the one responsible for verifying that the data is in an acceptable state for the operation which it is about to perform.
Addition of visual indicators of data validation problems to an editor form/window during editing is certainly nice to have. However, it should be considered more or less equivalent to view "eye candy", and it should be treated as an add-on to the real validation logic (even if it is based on shared metadata or code). The presenter (or controller) should remain the true authority for data validity, and its validation code should not be hosted in the view.
I believe view validation is only relevant in javascript as the view does not run any code on post, only the controller does.
But I would also not ever trust javascript validation as a malicious user could bypass it or an ignorant user might have JS disabled so repeat any JS validation in serverside code in the controller.
The view might have means to display any errors though .

Categories

Resources