ASP.NET MVC AJAX Database update - ViewModel vs Controller - model-view-controller

I've currently got a controller which passes a model to a view. The view will be making AJAX calls to the controller to make updates to the data rather freqeuently, and the model makes for a rather nice arrangements to make these updates.
I know that making changes to the database in the controller is bad form, and I would like to avoid doing it. However, creating a model on every call and handing the update data off to it, although it seems more correct to me, takes longer on each request, as the model needs to be initialized. Since the user is blocked from interaction with certain elements on the page during the update, this time can really add up across dozens of updates.
Which method is best? Simply making the updates in the controller to keep the application as interactive as possible, or initializing an instance of the model on every request to handle the update at the expense of speedy request processing?

I would suggest optimize your model and/or create a lighter version of it.
Why is your model taking too long to initialize? Is the initialization loading things that you don't need when called in this particular case?
Bottom line, I would move the saving logic to a model but would make sure the model is fast and optimal.

Related

Writing query in controller instead model

I wanna ask about if we write query in controller instead model. does it have any effect? such as load data become slower or others?
the data that i want to use is over 1000.
if not, what makes the load of data slow in web.
like the ajax request is needed 4-5 sec, and some is until 1 minutes
There is virtually no difference between running a query in a controller or a model except for the small (negligible) amount of overhead a model adds (if it were me I wouldn't worry about it). If you want to adhere to the MVC design pattern, database queries are typically done in the model, not the controller. But this is more of a stylistic thing in CodeIgniter as it is not strictly enforced as it is in other frameworks that use ORM.
With that being said, if you are experiencing long execution times I would recommend not getting all the data at once, and instead using load more, pagination, datatables, or a similar system to reduce the amount of records selected at once to something more manageable depending on your acceptable execution/response times.
You can test what works in your situation best by setting benchmark points: https://www.codeigniter.com/user_guide/libraries/benchmark.html
I have been working with CodeIgniter for some few years and what I have realized is to properly do your queries in models.
The idea of MVC is about code separation where the M(Model) handles or does the heavy liftings of the application which mostly relates to databases, the V(View) does the presentation that is where users of the system get to interact with the application and the C(Controller) acts as a messenger or intermediary between the Model and the View.
This releases the controller from lots of processes so that it doesn't have to query from the database, try to upload lots of data before then showing it on a view.
I always use the (I call it the little magic) {elapsed_time} and {memory_usage}to check how my application work per whatever logic I implement, you can give it a try.
I think this helps.

CakePHP 2.x Performance - Can I bring the View to the user before the Controller has finished working on the data?

I have a CakePHP 2.x app handling a tourism agency/operator's day-to-day sales and operations.
The Sales Model interacts with pretty much all other Models, because it needs client information from Clients, agent information from Agents, passenger information from Passengers (Not always the same thing as client), its payment information in Payments, tour info in Tours, flights info in Flights, etc.
Basically, when a sales staff person navigates to a specific sale, they need the screen to show them lots of information that come from other Models.
This has made the screen slower and slower to load.
I'm avoiding using cache, because this is a boots-on-the-ground type agency, meaning they're not just selling, they're actually doing the operations themselves. In this environment, information always needs to be the most up to date.
So, the question is:
Is there a way for me to bring the View to the user before the controller finishes handling every piece of data?
Like:
<?php
class SalesController extends AppController {
public function show($id) {
// Get easy/quick data
// Take user to the View
// Get the more time consuming data
// Feed it to the View as it becomes ready
}
}
I've been thinking I should just call the page with the simple data and then have the more complicated data come in after loading, with some Ajax and javascript, but is that the best use of the framework?
An average sale's screen takes about 10000 ms to fully load at this point. Over 6000 ms of that time is Idle frame. That means it's my Controller working in the background, right?
This is most likely not possible without breaking the "controllers should never echo data" rule, violating it can cause all sorts of problems, like the data not being returned in the test environment, headers not being sent, data not being read completely, etc.
If you know what you're doing, and you're aware about the implications, then you could probably get away with it, but the AJAX solution ist most likely the safer workaround.
In any case I wouldn't do anything before identifying where exactly and why exactly the time is spent, and figuring if there's a way to speed up things at the root of the problem!

Handling forms with many fields

I have a very large webform that is the center of my Yii web application. The form actually consists of multiple html form elements, many of which are loaded via AJAX as needed.
Because of the form's size and complexity, having multiple save or submit buttons isn't really feasible. I would rather update each field in the database as it is edited by asynchrously AJAXing the new value to the server using jeditable or jeditable-like functionality.
Has anyone done anything like this? In theory I'm thinking I could set up an AJAX endpoint and have each control pass in its name, its new value, and the CRUD operation you want to perform. Then the endpoint can route the request appropriately based on some kind of map and return the product. It just seems like someone has to have solved this problem before and I don't want to waste hours reinventing the wheel.
Your thoughts on architecture/implementation are appreciated, thanks for your time.
In similar situation I decided to use CActiveForm only for easy validation by Yii standarts (it can use Ajax validation), avoiding "required" attribute. And of course to keep logical structure of the form in a good view.
In common you're right. I manually used jQuery to generate AJAX-request (and any other actions) to the controller and process them there as you want.
So you may use CRUD in controller (analyzing parameters in requests) and in your custom jQuery (using group selectors), but you can hardly do it in CActiveForm directly (and it's good: compacting mustn't always beat the logic and structure of models).
Any composite solution with javascript in PHP will affect on flexibility of your non-trivial application.
After sleeping on it last night, I found this post:
jQuery focus/blur on form, not individual inputs
I'm using a modified version of this at the client to update each form via AJAX, instead of updating each field. Each form automatically submits its data after a two seconds of inactivity. The downside is the client might lose some data if their browser crashes, but the benefit is I can mostly use Yii's built-in controller actions and I don't have to write a lot of custom PHP. Since my forms are small, but there are many of them, it seems to be working well so far.
Thanks Alexander for your excellent input and thanks Afnan for your help :)

Edit a model over several views

Is it possible to have one model that you break up into several views so that the user is not overwhelmed by the amount of data they will need to input? I'm trying to build a turbo tax like interface where a question or two are asked, then the user clicks next to answer the next set of questions and so on.
The Model doesn't seem make sense to break up into more models. Since it is a single distinct entity, like a questionnare.
See similar question for a nice example:
multi-step registration process issues in asp.net mvc (splitted viewmodels, single model)
It is possible to use the same model for multiple views, but you should decide how you want to preserve the state as you go though this "wizard". One approach can be to cross-post between the views and keep the state in post data, but in that case you have to add a lot of hidden fields for all model properties that are otherwise not displayed in an input on the current view. Another approach can be to persist the partially filled model, with the additional benefit, that the user might be able to continue after a session timeout or another problem, but then you might need to clean up stale data and be flexible in the validation on the database level. You can also preserve the state in the session if you want. Finally, you can also keep the state in the browser independent from the post data and do only AJAX calls with the server until you reach the point when you want to save everything.

Wicket and complex Ajax scenarios

When a screen has multiple interacting Ajax controls and you want to control the visibility of components to react to these controls (so that you only display what makes sense in any given situation), calling target.addComponent() manually on everything you want to update is getting cumbersome and isn't very maintainable.
Eventually the web of onClick and onUpdate callbacks can reach a point where adding a new component to the screen is getting much harder than it's supposed to be.
What are the commonly used strategies (or even libraries if such a thing exists) to avoid this build-up of complexity?
Update: Thank you for your answers, I found all of them very useful, but I can only accept one. Sorry.
In Wicket 1.5 there is an event bus. Each component has onEvent(Object payload) method. With component.send() you can broadcast events and each component can check the payload (e.g. UserJoinedEvent object) and decide whether it wants to participate in the current Ajax response. See http://www.wicket-library.com/wicket-examples/events/ for a simple demo.
You could add structural components such as WebMarkupContainers, when you add this to the AjaxTarget everything contained in it will also get updated. This allows you to update groups of components in a single line.
When I'm creating components for a page I tend to add them to component arrays:
Component[] pageComponents = {
new TextField<String>("Field1"),
new TextField<String>("Field2"),
new TextField<String>("Field3")
}
As of Wicket 1.5 the add functions take array parameters [1]. Therefore elements can be added to the page or target like this:
add(pageComponents);
target.add(pageComponents);
Components can then be grouped based on which you want to refresh together.
[1] http://www.jarvana.com/jarvana/view/org/apache/wicket/wicket/1.5-M3/wicket-1.5-M3-javadoc.jar!/org/apache/wicket/ajax/AjaxRequestTarget.html
Well, of how many components do we speak here? Ten? Twenty? Hundreds?
For up to twenty or about this you can have a state controller which controls which components should be shown. This controller sets the visible field of a components model and you do always add all components to your requests which are handled by the controller. The components ajax events you simply redirect to the controller handle method.
For really large numbers of components which have a too heavy payload for a good performance you could use javascript libraries like jQuery to do the show and hide things by the client.
I currently use some sort of modified Observer-Pattern to simulate an event-bus in Wicket 1.4.
My Pages act as an observable observer since my components don't know each other and are reused in different combinations across multiple pages. Whenever one component receives an Ajax-event that could affect other components as well, it calls a method on it's page with an event-object and the ajax-target. The page calls a similar method on all components which have registered themselves for this kind of event and each component can decide, on the base of the supplied event-object if and how it has to react and can attach itself to the target.
The same can be archived by using the wicket visitor. I don't know which one is better, but I think that's mainly a matter of taste.

Resources