0

I'm writing ASP.NET/MVC application. I need to fill an Knockout observable with value, which is being passed through the URL. Let's say, for instance, that I want to open the following page:

http://example.com/Controller/Action?param=test

I want to put the value passed through the URL parameter to input:

<input data-bind="value: field, <?>"></input> <!-- Either set value to "test" here -->

this.field = ko.observable(<?>) <!-- or here -->

Solution 1

Since I have full control on generating HTML, I can create hidden field, populate it with value, and then jQuery my way to the observable, but it seem to be quite an overkill for me.

<input type="hidden" id="temp" value="@Model.Param"></input>

field($("#temp").val());

Solution 2

Another option is to generate some Javascript with Razor:

<script type="text/javascript" src="pageViewModel.js"></script>
<script type="text/javascript">
    pageViewModel.setValue(@Model.Param); // Dangerous
</script>

This is dangerous though - I would apply some security measures to avoid people injecting Javascript here.

Is there a better way to do it?

Spook
  • 25,318
  • 18
  • 90
  • 167

2 Answers2

2

You can access the query string though javascript directly in your knockout view-model by checking the window.location.search How to obtaining the querystring from the current URL with JavaScript?

var searchParams = new URLSearchParams(window.location.search);
this.field = ko.observable(searchParams.get("param"));

(The linked SO answer also has a solution for older browser support if URLSearchParams aren't supported)

Jason Spake
  • 4,293
  • 2
  • 14
  • 22
2

I like Jason Spake's answer better but this is how we do it where I work...

we have a utility function

// this is a utility function that returns query string values. Pass in the
// name of the query string and the value is returned
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

then we call it like this

this.HazInd = ko.observable(getUrlVars()["HazInd"]);
adiga
  • 34,372
  • 9
  • 61
  • 83
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79