Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
In most MVC applications when rending Razor Views, I think the tendency is to use the
IUrHelperl.Action
inside if anchor href or form action. If you are using ASP.NET Core, maybe you are using tag helpers like
anchor tag helper. But there’s another option I don’t see very often, which is creating the relevant routes and define them in your ViewModel within in your controller action. This can be really useful when you’re application’s available actions are driven by state.
Razor
Here’s a small example of a shopping cart. The view model has a list of products that are in your shopping cart. Something obvious would have the product title be a link to the actual product page. As mentioned you could do this using the UrlHelper or a tag heper.
Conditional Actions
But how do we handle if there are conditional actions on our page. For example, there are certain products that you can only purchase a maximum of 1 per cart. You cannot change the quantity.
If we are using our method above, we also likely need to include something in the view model to indicate if the action is possible. If it is not, we likely don’t want to render that relevant part of the page.
ViewModel
Instead, an alternative is to generate any links/actions and supply them in your view model.
Now in our razor, we can make the conditional on if the action exists.
Why?
If you generate view models that contain links and routes to actions, and are used in your Razor, what’s stopping you from taking that same view model and serializing it and returning JSON. The ability to add content negotiation and render HTML (via razor) or JSON (direct or more transformation) depending on the clients Accept header.
This is a simple example. but if you have a lot of UI that’s visibility is driven by state, then this is a great approach. Ultimately if you are also creating HTTP API’s, this should be a lead down the road to hypermedia.
Do you have any questions or comments? Are you using a similar approach? I’d love to hear about it in the comments or on Twitter.