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.
Related
I am working on ASP.NET Core project and have a dilemma: I have got a table of items filled from ajax request (from api controller). Now clicking individual item I want to open Details view - pretty simple.
But I have 2 choices:
1 - Pass item's id to my mvc "Details" controller, then from there call database again, get the requested object and return the view.
2 - Pass the whole JSON object to my mvc "Details" controller via #Html.ActionLink (since I already have one in my table), and build the view.
Choice #2 seems better at first sight, because I am saving extra trip to the database and all operation happens on the client.
But I have a hesitation if it's ok to do it this way (pass the whole objects via url) from all further prospectives, like security?
As you know I can't annotate my "Details" mvc controller with [ChildActionOnly] anymore, so the url query is easily editable.
If your models are large (or may become large in the future), you won't be able to serialize the whole thing to the URL. There is a limit of approximately 2000 characters.
It's more common to see an Id passed to the controller and a database call there to get the full model. Then, if at some point you no longer need or want to load the entire object model on the Index page, you will not need to change anything about how the Details page works. (Good separation).
I will select second choices for the sake of simplicity and separation. The performance saving of round trip to database is not significant since we are talking single item not batch processing or something iterative but we have elasticity and flexibility to change/extend.
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);
I have data in my controller that is being received from another rails app and database (this has to be in the controller) I want to get this data so I can validate it in my model before allowing another step in a wizard (see my other question for some code examples)
My Problem is that I cannot directly grab this data from the controller in my model as this violates MVC.
My Question is how would I go about checking the controllers data in my Model?
Do I have to load this data / true - false response in a view and then link this to my Model? (I don't really want this to show in the view and haven't quite worked out how to do this)
Do I need to pass this data to a route i.e example/data.json and then check this in my Model? (I also haven't worked out how to use this data.json from there in my model)
Any help / steering in the right direction would be very useful. (also i cannot use a gem to do this)
At first, please be double double sure that you don't validate a model by data which it does not contain by itself. Model should validate its current state but not a way it came to this state (e.g. which user put a model to this state).
At second, you should never use controller methods in a model. If controller contains some business logic, extract that logic into a third class which will be used by both controller and model.
Moreover, you have a data in a controller and you have an access to the model, right?. Therefore, if you are in a controller method, for instance in a before filter or action, you could take that data and pass it to the model, like this:
def controller method
hey_model.is_this_correct?(data)
end
If you say that that data must be checked after controller has responded to a request (for example, at the next wizard step, i.e. at the next request), then you definitely must store that value somewhere between requests.
This is the very point of stateless HTTP. No data is saved between requests until you explicitly do that. You could store your value in cookies or in database.
I understand that the question was a while ago but for those who are still searching, I found the exact answer, how to pass the information from the controller to a model.
With this line everything is solved
var = request.env['target_model'].sudo().function_in_your_model(data)
var is a variable in case you need to handle that data in the controller, target_model is the model where you want to send the data, function_in_your_model is the function where you are going to handle the data already in the model, and inside this function you send the data that you need.
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?
I am using the Redirect After Post pattern in my ASP.NET MVC application. I have
the following scenario:
User goes to /controller/index where he is asked to fill a form.
Form values are POSTed to /controller/calculate.
The Calculate action performs calculation based on input and instantiates a complex object containing the results of the operation. This object is stored in TempData and user is redirected to /controller/result.
/controller/result retrieves the result from TempData and renders them to the user.
The problem with this approach is that if the user hits F5 while viewing the results in /controller/result the page can no longer be rendered as TempData has been expired and the result object is no longer available.
This behavior is not desired by the users. One possible solution would be instead of redirecting after the POST, just rendering the results view. Now if the user hits F5 he gets a browser dialog asking if he wants to repost the form. This also was not desired.
One possible solution I thought of was to serialize the result object and passing it in the URL before redirecting but AFAIK there are some limitations in the length of a GET request and if the object gets pretty big I might hit this limitation (especially if base64 encoded).
Another possibility would be to use the Session object instead of TempData to persist the results. But before implementing this solution I would like to know if there's a better way of doing it.
UPDATE:
Further investigating the issue I found out that if I re-put the result object in TempData inside the /controller/result action it actually works:
public ActionResult Result()
{
var result = TempData["result"];
TempData["result"] = result;
return View(result);
}
But this feels kind of dirty. Could there be any side effects with this approach (such as switching to out-of-process session providers as currently I use InProc)?
Store it in the Session with some unique key and pass the key as part of the url. Then as long as the session is alive they can use the back/forward button to their heart's content and still have the URL respond properly. Alternatively, you could use the ASP cache, but I'd normally reserve that for objects that are shared among users. Of course, if you used the parameters to the calculation as the key and you found the result in the cache, you could simply re-use it.
I think redirect after post makes much more sense when the resulting Url is meaningfull.
In your case it would mean that all data required for the calculation is in the Url of /controller/result.
/controller/calculate would not do the calculation but /controller/result.
If you can get this done thinks get pretty easy: You hash the values required for the calculation and use it as the key for the cache. If the user refreshes he only hits the cache.
If you cant have a meaningfull url you could post to /controller/index. If the user hits F5 calculation would start again, but a cache with the hash as key would help again.
TempData is generally considered useful for passing messages back to the user not for storing working entities (a user refresh will nuke the contents of TempData).
I don't know of more appropriate place than the session to store this kind of information. I think the general idea is keep session as small as possible though. Personally I usually write some wrappers to add and remove specific objects to session. Cleaning them up manually where possible.
Alternatively you can store in a database in which you purge stale items on a regular basis.
I might adopt a similar idea to a lot of banks on their online banking sites by using one-time keys to verify all POSTs. You can integrate it into a html helper for forms and into your service layer (for example) for verification.
Let's say that you only want to post any instance of a form once. Add a guid to the form. If the form does not post back and the data is committed then you want to invalidate the guid and redirect to the GET action. If say the form was not valid, when the page posts back you need a new (valid) guid there in the form waiting for the next post attempt.
GUIDs are generated as required and added to a table in your DB. As they are invalidated (by POSTS, whether successful or not) they are flagged in the table. You may want to trim the table at 100 rows.. or 1000, depending on how heavy your app will be and how many rendered but not yet posted forms you may have at any one time.
I haven't really fine tuned this design but i think it might work. It wont be as smelly as the TempData and you can still adhere to the PRG pattern.
Remember, with PRG you dont want to send the new data to the GET action in a temp variable of some sort. You want to query it back from the data store, where it's now committed to.
As Michael stated, TempData has a single purpose -> store an object for one trip only and only one trip. As I understand it, TempData is essentially using the same Session object as you might use but it will automatically remove the object from the session on the next trip.
Stick with Session imho rather than push back in to TempData.