How does my MVC controller query one database table before writing to another? - model-view-controller

I am working on a custom Joomla MVC component.
My view has a form where the user enters an ID. I have retrieved the ID ($input_id) in the controller. Now I need to query the database to get the name WHERE ID = $input_id, then write the name to a different database table.
Can this all be done within the controller or do I have to pass my variables to the model somehow? Not sure of the correct way to achieve this within the MVC framework.

All data and data manipulation should be done in the model (e.g. model your data). The controller is there to determine the path of execution and which methods should be called (e.g. the manager aka controller determines what needs to be done).
Have a look at this tutorial which will help you understand MVC for Joomla better by taking you through the development of a simple component.

Related

ASP.NET MVC 3.0 - Maintain model state

Am new to ASP.NET MVC 3.0. Request expert's view on the below mentioned scenario.
I have a customer details page, where only Name is editable. There are 10 other customer properties that are non editable and displayed using SPAN. When user submits the page, I need to update only the Name.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
Anyone tried caching model (or viewmodel) using session id? Is it a good practice?
You are almost thinking in right direction.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
In Update Method **Load Customer again and update name Only as required and then save
**For 2 reasons
The first and most important rule is 'don't trust user data'. and
Concurrency and to avoid saving old data. See this example
Instead of using Session, I will suggest to use Hidden Field for record LastUpdateDateTime and Customer ID which will be posted back in the model to retrieve record and verify LastUpdatedtime with database record
Tipically, you should use a view model different than the database model. Having said that,in your current case the situation is very simple, submit only the name to the controller and then set the Name property of the object you get from EF with the submitted name.
Caching the view model or the model isn't your concern. The database model caching is handled by EF, your problem is mainly a lack of clear application layering. IN fact I strongly suggest to learn a bit more about the MVC pattern, basic application architecture (2-3 layering) and when and how to use a OR\M (which EF is).
use hidden inputs for other properties in your form. In that way you can get all properties binded to your EF entity and you dont need to get entity again from db.
#Html.DisplayFor(model=>model.x)
#Html.HiddenFor(model=>model.x)
or you can serialize the entity(if you use POCO entities) and set to hidden input. When you post back you should deserialize the entity.
My choice is always first one. :)

CodeIgniter MVC Model Logic

I have programmed in Rails, Django, Zend, and CakePHP. Also, Wordpress and Drupal.
Now, I am "catching up to speed" in as fairly large application in CodeIgniter.
Typically, my experience with MVC frameworks, has led me to believe that Models represent business logic in reference to actual database tables. In the CodeIgniter docs and in the code base I'm dissecting I see models created that represent something as vague as a page. A lot of the business logic is written directly into those models and they incorporate other actual data models. I'm not sure this is ideal and following MVC.
Should models be created beyond data models?
Also, lets say I have a data model representing a user (user table in DB). In that user table there is a column called gender of the type enum('male', 'female'). Now I want to populate a dropdown with the gender options from the enum column.
Where is it most appropriate to put this logic?
The user model is an object used to represent a single user or row in the db... right? So it doesn't seem fitting to include a function in the user model/class called "get_gender_options", because, while the function is related to the user table, it is NOT relevant to a single user object. In Zend this kind of logic could be built into the form object itself.
There is not "right" answer, just one we can consider the most appropriate...
I would probably just put the "get_gender_options" in the model, rather than sticking it in the view for the form. To keep it DRY but not put it in the model, I would create a helper to hold this.

ASP.NET MVC 3 how to implement many to many relationship in Create View

I have quite a complex class that has three one-to-many relationships and two many-to-many relationships with other classes. What I would like to do is to enable the user to fill all the details one by one - in one step or even better in multiple steps (wizard).
My class is called PeriodicTask - user has to select one Server object (which represents SQL Server instance ) and depending on the selection I need to present the user with the ability to select which databases he wants to use ( the best option would be to use checkboxes). I don't really know how to achieve this.
I would start with creating an action that returns JSON with databases for the selected server. It'll be invoked by jQuery. So far so good, but what to do then?
Should I add <input type="checkbox"> to the form for every database or maybe create another form and post to some other action? How to parse that when the form is submitted? Can I split it somehow into smaller steps ? HTTP is stateless so I somehow need to pass or remember the data that was previously submitted - how?
PS> I'm using Entity Framework here, so part of the class hierarchy is as follows:
You could do it like this:
User selects server instance from
dropdownlist.
After selection dropdownlist fires "change "event, handler of
which loads databases list to form using ajax (your action can provide JSON or html with checkboxes)
User selects checkboxes and presses
submit button
On submit you collect
checked item and post to action
using javascript
I would look at creating helpers for each of the options that would be self contained, they could maintain the state themselves.
Another cool option would be to create a tree view, where the root level is your server and next level is database. Load the data into a ViewModel so that it can be used as the data source for a tree view. It seems like a nice interface for what you have.
Believe it or not the Microsoft site is a great place to start when learning MVC
http://www.asp.net/mvc

MVC3 (Models) ...what is the right way to display complex data on the view?

I’m having a philosophical problem with understanding how to use Models on MVC3.
I believe the problem lies from the fact that I come from WebForms :--)
Let's say I have 10 tables on my DB and as expected when I get them into my EF4, I get those Entity classes that represent the tables (and all their FK integer values).
When I want to display data on the View, I cannot display a select * from table because those FK integers means nothing to my users …and also because some data lies on related tables.
So my understanding is that I can create a Stored Proc, create a Complex Type that represent the actual data to display, coming from separate tables via different SQL joins.
QUESTION 1:
On the view, id MVC compliant to use as #model ..that Complex Type?
or shall I always use Models that are created on the Models folder? And if so, does that mean that I have to replicate the Complex Type on a new model inside the Models folder?
Question 2:
Is this the right way …to create specific SP to collect data that will be displayed or ..is it better to use linq and lambda to be applied to the EF4 Types that come from importing the DB into the EMDX designer.
Thoughts ??
FP
The correct way is to always define view models. View models are classes which are specifically tailored to the needs of a given view and would be defined in the MVC application tier. Those classes would contain only the properties that would be needed to be displayed by the view. Then you need to map between your domain models (EF autogenerated classes?) and the view models.
So a controller action would query a repository in order to fetch a domain model, map it to a view model and pass this view model to the view. Top facilitate this mapping you could use AutoMapper. A view shouldn't be tied to a domain model and always work with a view model. This works also the other way around: a controller action receives a view model from the view as action argument, maps it to a domain model and passes this domain model to the repository in order to perform some action with it (CRUD).
So a view model could be a class that is mapped from multiple domain models or multiple view models could be mapped to a single domain model. It all depends on how your domain looks like and how do you want to represent the information to the user.
As far as validation is concerned, I distinguish two types: UI validation and business validation. As an example of UI validation is: a field is required, or a field must be entered in a given format. A business validation is : the username is already taken or insufficient funds to perform wire transfer. UI validation should be done on the view models and business validation on the domain models.
I'm not sure why you need to use a stored proc, LINQ to Entities is able to generate complex types without needing to create stored procs (in most cases). You select subsets of data, just like you would with regular SQL.
As Darin says, the use of a View Model is appropriate for situations where you have a lot of complex data that isn't represented by a single entity. This View Model would contain multiple entities, or even multiple collections of entities. It all depends on how your data needs to be consumed.

How should separated controllers access the model?

Given that I've got any number of controllers, how should they access the data saved in the model?
In a database driven application it's quite easy as all data can be fetched from one single object.
Should there be a namespace / singleton / global object which allows access to the data?
Should the model be passed to all controllers when they are created?
Some of the best practice being pass around is setting up a repository pattern like so within your model to abstract the data model form data mapping. I'd go into more detail but the first link gets you there.

Resources