Hi,
Ok, let's assume we are working with ASP.NET MVC 2 (latest and greatest preview) and we want to create AJAX user interface with jQuery. So what are our real options here?
Option 1 - Pass Json from the Controller to the view, and then the view submits Json back to the controller. This means (in the order given):
User opens some View (let's say - /Invoices/January) which has to visualize a list of data (e.g. <IEnumerable<X.Y.Z.Models.Invoice>>)
Controller retrieves the Model from the repository (assuming we are using repository pattern).
Controller creates a new instance of a class which we will serialize to Json. The reasaon we do this, is because the model may not be serializable (circular reference ftl)
Controller populates the soon-to-be-serialized class with data
Controller serializes the class to Json and passes it the view.
User does some change and submits the 'form'
The View submits back Json to the controller
The Controller now must 'manually' validate the input, because the Json passed does not bind to a Model
See, if our View is communicating to the controller via Json, we lose the Model validation, which IMHO is incredible disadvantage. In this case, forget about data annotations and stuff.
Option 2 - Ok, the alternative of the first approach is to pass the Models to the Views, which is the default behavior in the template when you start a new project.
We pass a strong typed model to the view
The view renders the appropriate html and javascript, sticking to the model property names. This is important!
The user submits the form. If we stick to the model names, when we .serialize() the form and submit it to the controller it will map to a model.
There is no Json mapping. The submitted form directly binds to a strongly typed model, hence, we can use the model validation. E.g. we keep the business logic where it should be.
Problem with this approach is, if we refactor some of the Models (change property names, types, etc), the javascript we wrote would become invalid. We will have to manually refactor the scripting and hope we don't miss something. There is no way you can test it either.
Ok, the question is - how to write an AJAX front end, which keeps the business logic validation in the model (e.g. controller passes and receives a Model type), but in the same time doesn't screw up the javascript and html when we refactor the model?