-1

I want to display a text with 2 links inside the text in MVC view! The text link are dynamic from server side and looks like this in controller:

Model.Message = "You have used up all your credits for this month (see  your credit balance {FirstLink}). You can buy credits {SecondLink}";

In view I have something like this

@{
var messageToShow = @Model.Message;

var newText = Html.ActionLink(Model.LinkText, Model.LinkAction, Model.LinkController, Model.LinkRouteValues).ToString();

var link = Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, Model.SecondLinkController, Model.LinkRouteValues).ToString();

}

@if (!string.IsNullOrEmpty(Model.LinkText))
{
    messageToShow = messageToShow.Replace("{FirstLink}", newText);
}

@if (!string.IsNullOrEmpty(Model.SecondLinkText))
{
    messageToShow = messageToShow.Replace("{SecondLink}", link);
}[![enter image description here][1]][1]

@Html.Raw(messageToShow)

This is working like it is but I have to add the class to it like this

@Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, Model.SecondLinkController, Model.LinkRouteValues, new { @class = "link" })

When adding the ,new{ @class = "link"} I got syntax error since the closing } is badly interpreted by razor engine.

Can you help out or maybe suggest a better solution?

Thanks

jdurc
  • 76
  • 3
  • 11
Dongolo Jeno
  • 414
  • 6
  • 8

2 Answers2

1

In order to solve the syntax error, your view model would need to include a property for the html attributes, either

public IDictionary<string, object> LinkAttributeValues { get; set; }

if LinkRouteValues is typeof RouteValueDictionary, or

public object LinkAttributeValues { get; set; }

if LinkRouteValues is typeof object

And then you code becomes

Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, 
    Model.SecondLinkController, Model.LinkRouteValues, Model.LinkAttributeValues)

Note that both your @if (!string.IsNullOrEmpty(Model....)) lines so of code are pointless since if either LinkText or SecondLinkText were null or an empty string, the previous Html.ActionLink(..) lines of code would have thrown an exception.

One option would be to simply use

<span>You have used up all your credits for this month (see your credit balance</span>
@Html.ActionLink(Model.LinkText, Model.LinkAction, Model.LinkController, Model.LinkRouteValues, new { @class = "link" })
<span>). You can buy credits</span>
@Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, Model.SecondLinkController, Model.LinkRouteValues, new { @class = "link" })

or if you want to set the message text in the controller, you could have 2 properties, say string Message and string Message2 and use <span>@Model.Message1</span>....

0

You don't need to prefix an '@' before the ActionLink when you're inside a code block. Remove that and I'm sure the syntax error will disappear.

jdurc
  • 76
  • 3
  • 11