Tuesday, 10 September 2013

Mixing Knockout and Razor Variables

Mixing Knockout and Razor Variables

I am struggling with what I imagine is a really daft problem. I am
iterating through a collection in Knockout.JS using 'foreach', and need to
create a link for each item using variables within the collection.
The problem is that my url is generated on the fly using variables from
the view model, and I need to combine these with variables in the Knockout
collection.
Here is my block containing the Knockout loop.
<div data-bind="foreach: pagedList" class="span8"
style="border-bottom: 1px solid #0094ff;">
<div style="cursor: pointer;">
<p data-bind="text: hotelId"></p>
<p data-bind="text: name"></p>
<p data-bind="text: hotelRating"></p>
<p data-bind="text: propertyCategory"></p>
</div>
</div>
Ideally I want to add the link to the parent div through the
'onclick="window.location=' method. I have tried using Action.Link and
adding in the Knockout variables through string concatenation, as so;
<div style="cursor: pointer;" onclick="window.location="@Url.Action(
"Index", "Hotel", new { regionId = Model.region.regionId,
regionName =
HttpUtility.UrlPathEncode(Model.region.regionNameLong.ToString().Replace(",","")).Replace("%20","-"),
hotelId = " + hotelID() + ", hotelName =
HttpUtility.UrlPathEncode(Convert.ToString(" + name() +
").Replace(",","")).Replace("%20","-") })"> </div>
But this gives an 'Object not instantiated error'. Secondly, I tried using
Knockout first, through the 'data-bind="attr:' method, as so;
<a href="someurl" data-bind="attr: { href: '/Region/' +
'@Model.region.regionId ' + '/' +
'@HttpUtility.UrlPathEncode(Model.region.regionNameLong.ToString().Replace(",","")).Replace("%20","-")
' + '/' + hotelID() + '/' +
'@HttpUtility.UrlPathEncode(Convert.ToString(" + name() +
").Replace(",","")).Replace("%20","-")' }, text: hotelId()"></a>
Again no dice.
I know this is mixing client side and server side paradigms, but can't
think of another way without ditching Knockout.
Does anybody have any experience with this?

No comments:

Post a Comment