I have a model containing an integer property called Pointer. I want to use that property inside the Razor view, as follows:
However I am getting an error...
How do I solve this? Is this error because of the line: int pnt = @Model.Pointer; ?
Yes, and you are generally overusing @. Your code should probably read something like:
@for (var i = 0; i < Model.Lists.ToList().Count; i++) {
var pointer = Model.Pointer;
if (i == pointer) {
var url = "/Subscriber/List/" + i;
<li><a href="@url">@Model.Lists.ToList()[i].ListName</a></li>
}
}
Apart from your actual question, I suggest you consider writing some extensions to the HtmlHelper class, i.e. to allow writing e.g. Html.SubscriberListItem(number), to keep concerns properly separated and the view clean.
Another option would be moving most of the logic to the view model (or possibly controller). I.e. there could be something like a Model.Subscribers.Link.Uri and a Model.Subscribers.Link.Text. This may even be the preferred option, depending on what your model looks like. (Perhaps the uri should be hooked up with the RoutingTable also.)
The code you've written is prone to throwing exceptions, and moving the logic out from the view will make writing safe code easier as well, if you don't mind my saying so.