Igor Levashov
Igor Levashov

Reputation: 328

Mixing Razor and Knockout syntax in data binding

I am trying to mix ASP.NET MVC Razor and Knockout syntax like this:

<a data-bind="text: CityName, attr: { href: /search/ + 'CityName' + '/@CurrentCategory}">
</a>

Where CityName is a knockout property and @CurrentCategory is an asp.net mvc property.

Visual Studio gives me an error about syntax.
Is it possible to do like that?

Upvotes: 0

Views: 994

Answers (2)

Bal&#225;zs
Bal&#225;zs

Reputation: 2929

Use this instead:

<a data-bind="text: CityName, attr: { href: '/search/' + CityName + '/@CurrentCategory' }">
</a>

You need to enclose the static or literal part of the string with 's and not the variable, or the dynamic part.

Also make sure you escape any 's in any fragment inserted by Razor. The above could be rewritten in order to achieve it as such:

<a data-bind="text: CityName, attr: { href: '/search/' + CityName + '/@CurrentCategory.Replace("'", "''")' }">
</a>

Upvotes: 5

a.tolba
a.tolba

Reputation: 149

we need to know the error to be able to help you accurately meanwhile you could try using a computed observable, so in your knockout controller create:

self.Url = ko.computed(function(){
   return '/search/' + self.CityName() + '/@CurrentCategory';
});

Upvotes: 0

Related Questions