I have an object named Camera in my MVC 3 application. I created a controller action and a view to edit Camera object. I have come across a couple of problems and I would appreciate it if anybody helped me. Here are the Edit action methods:
public ActionResult CameraEdit(int cid)
{
...
}
[HttpPost]
public ActionResult CameraEdit(Camera camera, HttpPostedFile file)
{
...
}
1- Camera class has some properties that I don’t want to show on the edit view (such as createdDate). So I removed the auto-generated tags from the layout. The problem is when I use TryUpdateModel to update the Camera object in HttpPost version of Edit action method (which takes in a Camera object as the first parameter), those properties I took out, won’t be populated and will be set to null. How could I resolve this issue? I know that MVC framework does its best to populate the properties by searching the form fields based on the name attribute, so when it doesn’t find any textbox with name ‘createdDate’, it fails to populate this property. But how would I hide this unwanted field? Things kind of contradict here!
2-My Camera class has an Image property that stores the path of the image. On the edit form, I want to put a file upload and just like the above case, I removed the auto-generated tags in the layout and instead a put an html file input. If a file is uploaded at runtime, how would I set the Image property of the Camera object (the first property of the Edit method) to be the new path entered by the user?
Use a view model. So instead of having your Edit actions pass and take a
Cameraobject make them pass and take aEditCameraViewModelobject. This is a class that you will define and which will contain only what is necessary for editing a camera and this specific view. Even the uploaded file could be a property of your view model so that you don’t have your POST controller action take 2 arguments. Obviously now the view will be strongly typed to the view model instead of the domain model.Then inside your controller actions map between the domain models and the view models. Personally I use AutoMapper to simplify this mapping.
This way you can keep all the autogenerated EF, specific stuff in your DAL layer and don’t bother with it in the frontend.