Reputation: 642
I'm new to MVC and I have a relatively basic question. I've found some answers through searching, but nothing that conclusively makes me feel like I know the 'best practice' for this common functionality:
I have strongly typed views and I have a relationship between 'Members' and 'Pets'. I want a page on my Member edit view to 'Create a new Pet'.
At this point, I'd like to pass the memberId from the Member edit view to the Pet create page so it can start a new instance of the Pet model with the correct member associated.
I'm thinking the best practice is to pass the memberId from the Member edit view (but by what method?) and then store this value in a hidden form field that is the correct name for the strongly typed 'memberId' value on the Pet model. Then, the Pet create controller should automatically pull this value when it's creating the Pet.
I need help passing the memberId from the Member edit view to the Pet edit view, and also general thoughts if this is the best way to accomplish what I'm looking to do. Thank you for your time and assistance!
Upvotes: 0
Views: 229
Reputation: 124696
The straightforward way is to pass the memberId as a route value to the CreatePet Action.
So your Member View might have a Url like the following to navigate to the CreatePet Action:
@Url.Action("CreatePet", "PetController", new { memberId = Model.MemberId })
And the CreatePet action would have the memberId as a parameter
public ActionResult CreatePet(int memberId)
{
...
}
UPDATE
From comment to question:
I was also curious if I could just pass the entire Member model in the 'Add a Pet' button and use that in the Pet Controller? This might be the preferable method
This doesn't sound like a good idea for a number of reasons. Why should the Pet need to know so much about the Member? And what if the client spoofs the Member values - you shouldn't rely on them, so would be better off looking up the Member server side using only the id that is passed as a route value.
Upvotes: 1
Reputation: 4609
So the way that is really preferred that I have seen for handling this kind of problem is the use of the MVVM pattern where you create a ViewModel object specifically designed for the view. While this may seem like, I have so many Views! But thats probably when you need to switch to dynamic views. However if you can not this pattern is a good one to follow for it. For instance you need a member id and the pet information I believe? What you can do is pass down an object that contains the list of pets, or something like that. Then in the view model you also pass down a list of member ids or the member id. I am not quite clear on the point of the application. But bottom line is you create a model that is specific to that view that also makes use of the actual models in order to pass down the necessary information. This links is a good description of it. http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx
Good luck.
Upvotes: 1