How to pass variable from one View to another View in link?
Ok, so I have this code in my view:
as you can see, in this view I am including a link to another view, I loop through a collection of objects and would like to pass the value of one of the fields of that object (Nome_grupo) to the view being linked to. I am doing it in the Razor syntax way because it seemed simpler, but I am open to any other way as this one has proved a bit wonky.
10 Replies
asp-route-{name}
In general, use the anchor tag helper
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-8.0Oh, I didnt realize
asp-route-
was a wildcard prefix, I thought asp-route-id
was the only valid attribute lol
thanks again ❤️
Hey, but how do I "retrieve" that variable in the destination view being linked?you'd take a parameter at the controller action with that name
id
in that caseDepends. Could be a part of the route, could be a query param
Could be a query param
ok, it's as a part of the route and it seems to be working as intended, I'm passing the id in a ViewData entry to the target view itself which I'm not sure is the perfect way to do it, but I think it seems correct enough
speaking of which, @ZZZZZZZZZZZZZZZZZZZZZZZZZ @Pobiega if I have more than one thing to pass as model to the view, generally speaking is it preferable to pass one as model and the rest inside viewdata or to create a viewmodel obj with all the data aggregated and pass that viewmodel obj??
viewmodel
10000000*10^123478154781%
Everything in the model
ViewData
is basically a Dictionary<string, object>
I only ever use it if I have to pass, dunno, the current page title from a page to the layout
And I think in the middleware that times the page generation
But I wouldn't use it to pass anything but simple primitives, and certainly not when there is a better wayI sometimes have two corresponding primitives and pass them both in a Dictionary through ViewData
stay mad
Jk, thanks for the advice guys