aman
aman

Reputation: 6242

knockout js pass view param

I have a parameter in my mvc view as

@{
   var myparam = false;
}

I have my button in the same view as:

 <input type="button" id="myButton" value="Click" class="btn btn-primary" 
  data-bind='enable: selectvalue() != ""' />

in the data-bind of my button I also want to check for myparam. Something like below:

data-bind='enable: filterCategory() != "" && !myparam'

How can I do that?

Thanks

Updated as below:

If my param is like below:

@{
  var myparam = false;
}

And my JS:

<script>
    var myData= @Html.Raw(Json.Serialize(Model));
    myData.myParameter= "@myparam ";
</script>

My Knockout:

  (function () {
    var viewModel = function (data) {
         var viemod= this;
         viemod.myParam= vmData.myParam
 }
}

If I use this myData in my knockout js as above it returns me "False" (string) whereas it should be false (boolean)

Upvotes: 0

Views: 42

Answers (1)

adiga
adiga

Reputation: 35222

That won't work because Razor runs server side. myparam is a C# local variable. So, you can't use it with knockout bindings which run client-side.

You can either create a javascript variable and assign the value like this:

<script>
    var myparam = @Json.Encode(myparam);
</script>

or

If you don't want to pollute the global scope, add a myparam property to your viewModel.

var yourViewModel = function() {
    var self = this;
    self.myparam = @Json.Encode(myparam);
    self.filterCategory = ko.observable('');
}

After update:

As mentioned before, it should be

myData.myparam = @Json.Encode(myparam);

But since you're going to .Serialize() the entire model, you can assign the myparam to a property in the controller itself.

Upvotes: 1

Related Questions