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?