Reputation: 959
I'm building a basic flashcard application - a Set contains Cards and other Sets. When navigating to something like Set1 > Set2 > Set3, I want each of the parent "Sets" to link to their respective details page. I'm passing the Details viewModel a string called "breadcrumbs", which contains something like this:
var stringBuilder = "";
var parent = model.ParentSet;
while (parent != null)
{
stringBuilder += "<li><a href=\"@Url.Action('Detail', 'Set', new {SetId = \" + parentSetId + \"}, null)'>" + parent.Name + "</a> <span class='divider'>/</span></li>";
parent = parent.ParentSet;
}
model.Breadcrumbs =
"<li><a href=\"@Url.Action('Index', 'Home')\">Home</a> <span class='divider'>/</span></li>" +
stringBuilder + "<li class='active'>New Set</li>";
model.Name = "New Set";
The URLs being generated are literal though - containing "@Url.Action".
Does anyone know how I can get this to work, or if there's a better way to do it?
Upvotes: 2
Views: 786
Reputation: 5351
I think an important question here is, "What does your view look like?"
If your view is using that model.Breadcrumbs field like this:
...
<div id="breadcrumbs">
@model.Breadcrumbs
</div>
...
The @Url.Action call in the string you've built will never be executed. The Razor engine operates on the code it finds in the view file, not on fields within the model.
You need to do one of two things:
Rather put "@Url.Action(...)" into the string you're constructing, figure out what the Url is on the server side using something like Url.Link() and insert that directly.
(and this is better) Pass those parents to the view as part of the view model and loop over them in the view, constructing the tags as you go. Normally you don't want to put html into a model. The model's there to hold data, not presentation code.
Upvotes: 0
Reputation: 34905
Just evaluate it:
"<li><a href='" + Url.Action('Index', 'Home') + "'>..."
Upvotes: 1