ASP.NET MVC "Loading..." gif during initial API call - asp.net-mvc

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.

Related

select2: load remote data from several sources simultaneously

I need some kind of omnisearch: when user types some name or serial number select2 sends several simultaneous ajax calls to retrieve employees, candidates and devices.
As soon as any of these calls returns data (for example employees) it is shown to user.
So if employee data is returned first we show it. As soon as candidates data is returned we combine it with employees data, sort data by name and show it to user again.
Is it possible?
You need to code by yourself such a thing, by default select2 only loads data attached to the select box, it's your responsability to write javascript that will behave in the following way and it's a non-trivial code.
In general your idea will be load (with multiple async calls) the locations you want and store the data you fetched, after performing operations you need (merging with another json) in the select box and refresh it.
I would think you would want to write this on the backend. Have an endpoint that collalesses all the data you want. Select 2 makes one ajax call to the endpoint to retrieve all the data you need in one go.

ASP.NET MVC 4 - Update Model from View

I'm playing around with ASP.NET MVC 4, but I have some problems with understanding. For better explanation I will use a simple "synthetic" situation.
Let's say I have model Person with 2 properties:
string Name
PersonType Type (e.g. Student, Employee, Military...)
Let's say in my controller I have private property Person. I can initialize this object in Index method, pass into View and build html page. Ok.
Now when user updates one of fields of person instance at the client side (he can input a new person name or select new person type using dropdown list), I want to update my model immediately. So, my general question is How can I achieve it?
Obvious solution for me: I can send an ajax request to controller from JS with new data. I thought that I can call controller's method UpdateName(string name) and update manually property Name with new data. BUT my person instance is NULL inside of this method! My second question is Why I can't access to initilized model object from other method? I think it's all about my bad understanding of client server interaction.
The final case of my situation: when user click's on the button "Save" I want to save created person into file on the server side, but I don't want to use any forms and receive all needed data just after clicking this button (because in my real task I can't use forms and also I can't receive all needed fields from html page after button clicking).
I have found the dirty solution. In JS I created another class Person with same properties. Now I can update instance of this class when I want and pass json data to server for saving it.
Is there any better solutions?
Its not that dirty to have javascript objects to represent your model. In fact thats how I do it. I use KnockoutJS to give me a client side model - which is essentially the MVVM pattern.
You are trying to use the MVC model in a way which you can't. However, the Knockout model you can use how you wish. You basically have a javascript representation of your server side model and once you are done with it you send it to the server.
In order for your server side methods to pick up your client side model you simply have to ensure the post request contains the data and as long as properties names are the same in the parameters of the method they will match themselves.
Why I can't access to initilized model object from other method?
Because it's not initialized anymore. Don't use the controller class to store persistent data across requests. The controller object is disposed after a request completes and then re-initialized on a new request. So anything that one action methods saves at the class level is gone when you get to another action method. Each request from the client to the server should be considered a fully isolated event, independent of any previous requests.
When you want to save your model, what you would do in that action is re-fetch it from the database, apply the changes, and save it back to the database.
but I don't want to use any forms
I'm not really sure what you mean here. Do you mean you want to use AJAX instead of POSTing the page directly? If so, that's fine. There are probably a number of tools out there to help you, personally I often just create a form anyway but instead of a submit button I have a plain button and add some JavaScript code (using jQuery) to serialize the form and perform an AJAX POST.
As long as the keys for the POST values map to your model fields in the same way they would in an out-of-the-box form, then your action method will still be able to receive the proper model type. On the server-side it doesn't matter if it's from an AJAX call or a normal POST. The difference, however, is that the response for an AJAX call should probably be in JSON format instead of responding with a view.
So instead of this:
return View(someModel);
You might have something like this:
return Json(someModel);

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.

Refresh several partial view

Is there a way to refresh several partial view from the controller ? (return View())
Thanks,
Update1:
Example, the content pârt of my screen is divided in 2 parts, on the left a customer list on the right the details customer, the details of the customers selected in the list of the left. If I create an new customer, when I save, I'd lile refresh the list (left part) and see the details (right part)
Kris,
the only way i can think to do this simply is by having multiple partialviews embeded within the main 'view' to be refreshed. these would then be refreshed in the same cycle. alternatively, you could have custom html helpers embedded within the main view that ran approprite code when the view was refreshed.
As for multiple views from a single action, i don't think this is both a good idea or in any way possible.
of course, rules are there to be broken :)
I don't think there is any automatic way to do this, but you could use some convention and:
Create a custom view result that takes in multiple partial view results i.e. a MultiplePartialViewResult
In the execute of the custom view result, call each the execute method of each of the supplied views'. Make sure to wrap each in a div or some other container for ease of retrieval at the client script
Upon receiving the response on the AJAX call in the client script, grab the value from each container and replace it in the corresponding elements matching the partial views initially rendered
For the last step you could use a convention. A simple one would be (if there is only one instance for each partial view) to put the id of target html element to update in the div/container you used to wrap it in the second step.
Based on what you're saying, I think using javascript and ajax to refresh from the server would be best.
You could use Html.RenderPartialAction to achieve DRY by putting it on the page, and then loading it using ajax and javascript.
If you were using jQuery, then something like this would work:
jQuery("#divToReload1").load('Url/To/PartialAction')...
jQuery("#divToReload2").load('Url/To/PartialAction')...
Just put that all inside one function and you'll reload all your partials at once.
You can send data through using the data parameter and catch the callback function to do as you wish.

ASP.NET MVC Ajax

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

Resources