ASP.NET MVC Ajax - asp.net-mvc

I would like to have a page that checks for updates to a database table and refreshes the grid using an Ajax call and when a new row is inserted into the table pop up a message window.
This database table gets updated with new rows every 15 minutes or so and the message window lets the user know that a new record has been added or possibly more than one record.
I'm wanting to do this in ASP.NET MVC with Ajax but have no idea how to go about setting up the javascript to check for updates on a timer or if there's a flag that the XHR uses to indicate a change in state.

You should try PokeIn library. It helps you to notify connected clients based on server side events. Here is a basic scenario;
Single static timer runs on the server side and checks any changes on DB. If an update is available sends it to connected clients / associated groups etc.
Samples are available from

This could be a possible way to do it:
Store the time when the data is aquired in a global variable in javascript.
Every x minutes, you do a javascript call to an action method with the timestamp as parameter. This can be done for example using the jQuery Timer as suggested by Rony.
The action method checks the database to see if anything has changed or not, and returns a simple boolean 1/0.
If, and only if, the data has changed, you get the new data from another action method and notify the user that new data has been retrieved.

you can use jQuery timers to check the state of the database using ajax and then modify the values in the table accordinly

Related

iOS tableview cell server sync timing

I'm developing network base app.
There is database model A (e.g. contact), which is displayed by tableView.
User has local databse (e.g. realm) in the client and server receive the data when user signup this app. The record of model A is modified by the button in the tableViewCell. (e.g. change group of contact or add user tags of that contact)
The data modification is up to only user. Server-side can not modify the model A, only read the model A.
Ok. Here is the question. When the user open the table view and modify the record of model A, server-side record need to be updated. Then, what timing should I write the server request code? There could be several scenario.
At the touchupinside event of the button in the tableViewCell, dispatch asynchronous thread and request server to update the item using this REST API : (POST) http://{server}/modelA/update/{id} . And when the request returns success response, update the local database.
Same as method 1. But differ the server request timing. At the touchupinside event of the button in the tableViewCell, only update the local database and set the dirty tag. And when user dismiss the tableView, at the ViewWillDisappear, request server to update dirty items using this REST API : (POST) http://{server}modelA/updates . In this way, we can reduce the number of server request to one and save network resource.
Which way is more suitable? I think that these task is common to networing app but can't find any advises.

Best MVC way to handle multiple requests between view and model

I have a .net application with a Form layer, a DB model layer (entity framework) and a Controller layer between this two layers.
I need to handle this situation:
User presses a button to edit some params
The form needs to request some DB data that represents the current state of those params
Possibly, the user request could be rejected because is N/A to current situation, in this case an error message box should be shown
A modal form is shown, the user changes params and confirm
Changes are made in the DB model
That's pretty simple.
The fact is that, at point 4, we need some of the data we already processed at point 2.
In particular:
at point 2 we request some data to the DB model, that data is likely not to be in cache, so a SQL query is performed
that data is processed by a local LINQ
state of several checkboxes to show in the modal form is returned
at point 4 we need again LINQ processed data
since we came from the Form layer, we do not have that data anymore
therefore data is requested again to the DB model, but this time it's in cache
that data is processed again by local LINQ
Is it worth to re-load and re-process data to maintain the MVC pattern?
I don't know how it works exactly in VB.NET, but if we look at this problem in a pure "MVC" way (at least, how I understand it), something is not right.
In this step, when the click is done, the form call the controller (all action pass by the controller)
The controller then needs to do the validation. If it needs the database to do that, so be it. Then, it redirect the user to a view. (Should it be a message box or another form to enter data)
Here, the user do the change in the form and then click on a button to submit. In this button, you call the controller again (another function/action).
In the controller, you can do the needed validation and insert/update the data in the database via LINQ. Then, you can redirect to the view.
Since a lot of time could have passed between the step 2 and step 4 and that the data could have changed between the 2 calls, I think that doing the request 2 times is ok. Also, since they are 2 different function in the controller, I don't think you have the choice.
That's how I see it, but I can be wrong :)
EDIT
I didn't know that the query to the database were time consuming and that it was an issue.If the absolute goal is to NOT make the user wait twice since time is important in this application, I guess you could store the object that you get at step 2 in memory and retrieve it with the controller (with some kind of helper class). It's like doing the query in the database, but in the memory. If you use the repository pattern, then the programmer who's coding the logic in the controller will not even know that he's querying something else than the database since it's another level of abstraction. You could free the memory right after the step 4.
Oh I'm not 100% sure but the flow pattern in your question does not look right?
The usual procedure is to DISPLAY the DATA and have an edit button there with the dataview
So you may have something like
Function ShowAddressDetails(OwnerId as long) as ActionResult
And your ActionResult is usually a MODEL that is to be passed to the VIEW
maybe (keeping with the address record sample) something like...
Return View(AddressRecordModel)
where the address record is extracted from SQL DB using the OwnerId parameter
And in your VIEW where your EDIT button is,
You have at least two choices,
Those being
1. Reload data from SQL (used where data may have changed since last action)
2. Pass the already loaded Model (Used where the data hasnt changed)
which would mean tha you have either (or both) of the following
Function EditAddressDetails(OwnerId as long) as ActionResult
or
Function EditAddressDetails(Model as AddressRecordModel) as ActionResult
Alternatively you may have "CHILDACTION"s as opposed to "ACTION"'s
Also do not forget the following...
in a HTTP GET request, the model is passed from the CONTROLLER TO the VIEW
in a HTTP POST request the Model is passed from the VIEW to the CONTROLLER
So you should indeed have the model (data)?
Finally if the sequence is ONLY used by ONE user then the data should not have changed between requests UNLESS and EDIT/AMEND/UPDATE request was completed successfully.

ASP.NET MVC "Loading..." gif during initial API call

I'm creating an ASP.NET MVC 4 web application that displays different data depending on the id number in the query string. It's designed to give users safety information specific to them based on what county they live in, what type of job they have, etc. They don't use a user name to log in, they just click on a link in their email like: http://www.mysite.com?id=123456
In Session_Start of global.asax, I pull down their id from the query string and search for a record that matches through an API call. This returns a bunch of fields in a DataSet which I turn into a DataTable. I then use a foreach loop to loop through the DataTable and use Session.Add(name, value) to create the session variables which I will plug into the view.
It can take up to 10 seconds for the API call to go through, so I want to put up some sort of "Loading..." gif animation until the API call is complete. Once the initial API call is complete I don't have to do any more API calls.
What's the best way to accomplish this?
If you need a loading animation, then you need a rendered HTML page. That means making your API call via AJAX. You can still encapsulate the call in your own view, just call your view with AJAX. Once you're initiating the call with JavaScript, it's trivial to add a loading animation. If you don't use AJAX, there's nothing you can do about it, as the server won't return the response until the view has finished processing.

How to send data generated from one http post to a second http post in ASP.NET MVC?

I have a view that is being used to create an invoice. The process should be as follows:
1. The user specifies a customer from a drop down and then a start date and end date.
2. They then click on a submit button, which is linked to the controller. This then builds an IList of all the jobs that meet the above criteria.
3. The page refreshes and displays the list of jobs.
4. On the same page, there is a second form which asks for an "Invoice Date" with another submit button. Clicking this should then Update an Invoice table in my DB whilst also looping through the IList of jobs and attaching invoice ID's to them (which are stored in another table in my DB).
The issue I'm having is that I've built a method which accepts the invoice data and the IList of jobs, but when I try to pass over the IList on the second submit controller method, it's null.
In the above scenario, what's the best way to get the IList built in the first post to be used in the second post?
The only way I can think of is using some sort of temporary table to store the list of jobs after the first post and then read from this in the second when updating the invoice table. Is this an acceptable method to achieve what I want? Or is there a better way that my lack of experience is missing? xD
What bugs me about that method above is that if the user leaves the page before posting the second time, the temporary table will then have a list of rogue jobs which could be called up unexpectedly the next time.
Hope I've explained this well enough. Thanks in advance.
The temporary table that you can use (which is built in MVC) is the TempData dictionary. It's persisted inside the Session, and the values get deleted when you use them.
BTW, have you thought of using Ajax instead of posting and refershing? This means that you always have the data with you, as you're on the same page. You don't have to carry state around.
UPDATE:
Errr wait, when you say that the list is NULL are you talking about a List recieved in your Action as a parameter? If you are, this article shows how to databind a collection.
UPDATE 2:
I have had second thoughts about using this method (getting data from the client), as it could lead to some security issues.
If you don't want to query the DB again, TempData/Session is a possible solution.
Since the list of jobs is not modified by the user on the second page, why don't you just grab it again in the controller action that handles your second submit?

ASP.NET MVC: where to keep entity being edited by user

Here's a simple problem: users want to edit products in grid-like manner: select and click add, select and click add... and they see updated products list... then click "Finish" and order should be saved.
However, each "Add" have to go to server, because it involves server-side validation. Moreover, the validation is inside domain entity (say, Order) - that is, for validation to happen I need to call order.Add(product) and then order decides if it can add the product.
The problem is, if I add products to order, it persists changes so even if users do not click "Finish" the changes will still be there!
OK, I probably shouldn't modify the order until users click Finish. However, how do I validate the product then? This should be done by the order entity - if product is already added, if product does not conflict with other products, etc.
Another problem, is that I have to add product to order and "rebuild view/HTML" based on its new state (as it can greatly change). But if I don't persist order changes, the next Add will start from the same order each time, not from the updated one. That is, I need to track changes to the order somehow.
I see several solutions:
Each time the user click Add, retrieve order from database, and add all new products (from the page), but do not persist it, just return View(order). The problem is I cannot redirect from POST /Edit to GET /Edit - because all the data only exists in the POST data, and GET lose it. This means that Refresh page doesn't work in a nice way (F5 and you get duplicated request, not to mention the browser's dialog box)).
Hm, I thought I can do redirect to GET using TempData (and MvcContrib helper). So after POST to /Edit I process business logic, gets new data for view, and do RedirectToAction<>(data) from MvcContrib that passes data via TempData. But since TempDate is... temp... after F5 all the data is lost. Doesn't work. The damn data should be stored somewhere, this way or another.
Store "edit object" in Session with the POST data (order, new products info). This can also be database. Kind of "current item - per page type". So page will get order ID and currently added products from this storage. But editing from multiple pages is problematic. And I don't like storing temp/current objects in Session.
Marking products as "confirmed" - if we do /order/show, we first cleanup all non-confirmed products from the order. Ugly and messy logic.
Make a copy of the order - a temporary one - and make /Edit work with it. Confirm will move changes from temp order to persisted. A lot of ugly work.
Maybe some AJAX magic? I.e. "Add" button won't reload page but will just send new + already added products to server, server will validate as order.Add(products + newproduct) but will not persist changes, will just return updated order information to re-build the grid. But Refresh/F5 will kill all user-entered info.
What else?
Is this problem common? How do you solve similar ones? What's the best practices?
It depends a lot on how you implement your objects/validation, but your option number 5 is probably the best idea. If AJAX isn't your thing, you can accomplish the same thing by writing the relevant data of already-added-but-not-saved entries to hidden fields.
In other words, the flow ends up something like this:
User enters an item.
Item is sent to the server and validated. The view is returned with the data entered by the user in hidden fields.
User enters a second item.
Item is sent to the server, and both items are validated. The view is returned with the data for both items in hidden fields.
etc.
So far as F5/Refresh killing entered data... In my experience this isn't too much of a problem. A more pressing concern is the back/forward buttons, which need to be managed with something like Really Simple History.
If you DO want to make the page continue to work after a refresh, you need to do one of the following:
Persist the records to the database, associated with the current user in some way.
Persist the records to session.
Persist the records to the query string.
These are the only storage locations available that persist through both redirection and refreshes.
If I were you, I would come up with something which resembles option 5. And since you say that you are comfortable with Ajax you can try this. But before you do this, you should move your validation logic outside the Order.Add() method. Maybe you can move it to another public function called Validate() which returns a bool. And you can still call the same Validate() in the Add() method, thereby doing the necessary validation before you add the order.
Try to do the validation on the client side. If you are using jQuery, you can use the jquery validate plugin. But, if this is not possible for some reason (such as when you need to validate stuff against a database). You should do your validation on the server side and just return a JSON object with the 'success' boolean flag and an optional message, just a way to mark that the data is valid. You would allow the user to add a new product only if the previous Order was valid.
And when the user hits finish send the product to the server and do the validation again, but persist the order in this round-trip.
Now, If I had a complete say in this, I wouldn't even go to the extent of doing validation whenever a product is added/edited. I would just do the validation whenever the customer hits finish. That would be the simplest solution. But, maybe I am missing something.

Resources