Spring Data, updating MVC partial entity - spring-mvc

I'm new to Spring, Spring data and Spring MVC so I want to make sure I am not missing something.
I have a form for updating a User object, the form posts to a controller and the controller calls my service class that updates/add the entity using a UserDOA which extends CRUDRepository. I think this is a very basic test code.
The issue is that the form doesn't contain all the fields in my User class, so when the object is posted to the controller, only the fields that are contained in the form are populated and the entity fields that are not in the form are null. For example my user has 4 fields, firstname, lastname, age, password. The form only contains the first 3 fields so when the object is posted to the controller, the password field is null, that is as I expect. My issue is that if I then call save(entity) on my DAO it will update the user but that would include nulling the password field, which of course is undesirable.
Of course I could simply retrieve the original entity from the repository and merge it with only the fields that have been updated, but it seems to me this is a lot of work that would be very commonly required and typically spring has a solution to these types of generic tasks.
Did I miss something?
TIA

Related

Trying to obtain the current logged in user's ID for tracking fields

I am following this really good tutorial to setup a BaseEntity class that will contain 5 fields:
Active, DateCreated, UserCreated, DateModified, UserModified.
All of my entities that need these tracking fields will inherit from this class.
In the small tutorial below he shows me how to override the SaveChanges() method in my dbContext so that these fields will be set properly based on Creation/Updating.
I am trying to figure out how I would store the current logged in user's ID rather than the Name to the UserCreated and UserModified fields
Please let me know if the UserID shouldn't be what I am storing. This is always what I used to do in some of the webforms apps I created back in the day.
Also, what would be the best way to setup Active to always be true when adding new records. Should this be done in the db context also or within my BaseEntity class. I'm thinking I would create a function in the BaseEntity class called Disable() that will change Active=False.
Please view the small tutorial that I am using
You could create a custom implementation of IIdentity/IPrincipal which contains the UserID. Then you can retrieve this value from the Context or Thread and cast it to the correct type.
Set HttpContext.Current.User from Thread.CurrentPrincipal

MVC5 Entity Framework Partial Class Extended

I've a problem about ASP.NET MVC5 and Entity Framework.
I work with an existing software database.
There is a table named "CLI" with lots of fields.
In my website, I've an Entity named "CLI".
A "CLI" can be a client or a delivery address (it's the same table). The only difference is the value of one field (C_LIV_SEUL)
I've a partial class "CLI" with DataAnnontations likes "Required" etc. on multiple fields.
The problem is that a Client and a Delivery Address doesn't have the same "Required".
Per example, for a Client, the field "C_NOM" is required.
For the Delivery Adress, "C_NOM" is not required.
In my view, when I've a form to update a Delivery Address, I don't display "C_NOM" because it isn't required.
But when I've a view to update a Client, I display "C_NOM" because it's required.
How can I do this ?
I think about inheritance, but I can't apply changes on datacontext (because it isn't a "CLI" entity), or add an Entity with the type "Client" or "DeliveryAddress"...
I also try to work with the ModelState (ModelState.Remove("C_NOM")), but when I SaveChanges the error persists.
Thank you all for help!

what is db.SaveChanges() in asp mvc4

I searched on many site about savechanges but i dont get any proper
answer can any one tell me about
db.SaveChanges()
ModelState
db.SaveChanges() is not part of ASP.NET MVC - it's part of Entity Framework which is a set of Object-Relational-Mapping (ORM) tools for the .NET Framework. All this method does is persist (save) data in some of your classes (entities) into a database.
Useful links:
Scott Gu - Code-First Development with Entity Framework 4
MSDN - Entity Framework
ModelState is a part of MVC and allows extra binding metadata to be passed from the Controller to the View, which is typically largely about validation.
Useful links:
MSDN - Model State Class
MSDN - Performing Simple Validation
msdn says : It persists all updates to the data source and resets change tracking in the object context.
Example
To save the changes made to the entities to a database, we need to call the ObjectContext class SaveChanges method. In the example given below, the query retrieves the first customer from the entityset -Customer.
var customer = context.Customer.First();
The context.Customer returns the Objectset of Customer types and the LINQ extension method First() returns only the first customer.
customer.FirstName = "Yasser";
customer.LastName = "Shaikh";
context.SaveChanges();
We can edit the first customer details like name and address by assigning new values to the properties and call the SaveChanges() method to save the changes back to the database.
During SaveChanges, the ObjectContext determines which fields were changed. In this example, only FirstName and LastName are changed. So, only those two values are sent into the command. To identify the row to be updated in the database, the ObjectContext uses the value of the EntityKey property.
Please read:
http://msdn.microsoft.com/en-us/library/bb336792(v=vs.110).aspx
http://www.asp.net/mvc/tutorials/older-versions/models-(data)/performing-simple-validation-cs
This should help you a little. Basically the db.SaveChanges() method is used by Entity Framework to save current changes to the database and ModelState represents validation errors when e.g. the model is not valid.

Using different servlets for different pages

I'm programming a car-hire web-site as my university project. There are some restrictions like * no JavaScript*, i can only use .jsp and servlets.
I've got few forms, i.e. booking form for customers, form to edit vehicles fleet for manager, etc. Lets say that data entered in the form needs to be validated and saved to a database. So i was thinking of checking weather the data is valid with the help of a servlet.If some field/fields were filled incorrectly i want (with the help of my servlet) to reload the page with form and to ask to re-enter data.
Question. How do I reload a page with a form on it with a help of servlet suggesting that some changes to this page should be made (highlighting of problematic fields, label stating that smth went wrong, etc.)?
Thanks for considering my question.
This is a basic functionality of every MVC framework (Stripes, Spring MVC, Struts, etc.). The idea is to have a servlet prepare a bean with default (usually empty) values, store this bean in a request attribute, and then dispatch to a JSP which displays a form populated with the values stored in the bean.
When the form is submitted, another instance of the same bean is populated with the request parameters, then validated, and if an error is found, the servlet stores the bean in the same request attribute as before, and also error messages in another request attribute. It then redispatches to the same JSP. This JSP redisplays the same form, and thus redisplays the value that the user has just submitted. It also displays the errors stored in the request attribute (and which was null when the JSP was executed for the first time).
Each error message can be associated with a form field name, so that the JSP can, for example, associate an "error" CSS class to a field if an error exists for this field.

Need help designing to ASP.NET MVC action methods

I'm just starting out learning ASP.NET MVC 3. I've been going through the Music store sample on the ASP.NET website, as well as starting to develop my own site, but I'm having some trouble understanding how I should setup my controller action methods.
On my site each user that is logged in will be able to perform standard CRUD operations on their Projects. I've set this up similar to the Music Store sample with the following action methods on a ProjectController. So far this makes sense to me.
ActionMethod View
ProjectController.Index() Lists the active users's projects
ProjectController.Details(int id) Shows details for project 123
ProjectController.Create() Shows a form to edit a new project
ProjectController.Create(FormCollection col) Adds a new project with the form contents
ProjectController.Edit() Shows a form to edit a new project
ProjectController.Edit(int id, FormCollection col) Adds a new project with the form contents
ProjectController.Deiete(int id) Shows a delete confirmation form
ProjectController.Delete(int id, FormCollection col) Deletes a project with the provided id.
In addition, users will be able to add Items to each project. Items can not exist on their own and must be associated to a project when being created. What I'm having trouble understanding is how to pass along the reference to the project an Item should be created in. For example in my item controller I have a pair of Create() action methods similar to the controller above.
ItemController.Create() Shows a form to create a new item
ItemController.Create(FormCollection col) Creates a new item with the details from the form.
Yet I don't understand how the first Create() method passes a reference to the project which the new Item should be created in since the View() helper method can only accept one object parameter. Should I just add a reference to a project to a property of the ViewBag? I'm new to dynamic types as well and the ViewBag just seems magic to me at the point. So I'm a little hesitant to use it. I've also always thought strongly typed design is better. So should I create a separate "NewItemData" model object that contains a reference to a new Item as well as the project it is being added to?
Once the form knows which project it is adding an item to how should it pass this information back when submitted? Should there be a hidden "ProjectID" field in the form? Or should the form POST back to a URL with the project id in the query string?
www.mysite.com/Item/Create?ProjectID=1234
Finally, I also want to be able to list the items that are added to each project. Should this be part of the ItemController or the ProjectController. For simplicities sake I'm sticking with the default Controller\Action[ID] URL routing. A few of my ideas are listed below. I'm leaning towards the last option, but would really like to hear what others with more experience with this stuff think.
Action Method URL
ItemController.Index(int ProjectID) \Item?ProjectID=1234
ItemController.List(int id) \Item\List\1234
ProjectController.Items(int id) \Project\Items\1234
To answer your last question, it depends. Do Items in your model exist independently of a project? If the answer is no, then I would tend to do
ProjectController.AddItem(int id)
ProjectController.Items(int id)
where id represents the projectID.
The name of the parameters you use in the action signature directly correspond to values from the routedata and request values. {controller}/{action}/{id} is a pattern that uses the braced names as keys in the route dictionary. If you wanted you could change the routes to be {controller}/{action}/{projectid} for that action and your method signature could be the (int projectid) signature.
I don't recommend you do this just to get awesome signatures. Use comments instead if you think people will get confused.
Without changing the route pattern, if you would prefer your urls to be /project/items?projectid=3 than /project/items/3 then the action would be this:
ProjectController.Items(int projectId)
I like the prettier urls, so i'd be more apt to use the id version. That being said, if Items do not exist independently of the Project object, I would be be more likely to do this. However, if you are going to have a TON of different actions that can be performed on an Item, it would make sense to separate them into ItemController and ProjectController.
It comes down, to a large extent, about what makes sense for your application and how many actions you think a controller should have on it.
In this case you'd create a hidden field with the name=projectId and then in your Create controller have an action method.
[HttpPost]
public ActionResult Create( int projectId, FormCollection postData )
Usually you'd also use a strongly typed viewmodel so instead the FormCollection parameter use:
[HttpPost]
public ActionResult Create( int projectId, Item or ItemViewModel postData )
And as long as the name attributes match the properties in Item or ItemViewModel MVC's ModelBinder will take care of hydrating those values.

Resources