[英]How to call javascript function in a JS file to a controller using ASP.Net MVC?
[英]how to build dynamic call to javascript function using asp.net mvc and knockoutjs
我正在使用模板HotTowel(您知道durandal,淘汰賽,微風等)構建mvc應用程序。 該應用程序尚未准備就緒,但我們正在取得良好進展:)。 在一個功能的中間,我需要構建對javascript函數的動態調用。 使用硬代碼值的調用類似於:
<a href="#" id="openreport"
onclick="showReport('@Url.Action("Index","Report", new { Id= 9, languageId = 2})');">Show
report</a>
通話上方功能正常。 當我嘗試使用基因敲除法將onclick事件綁定到字符串屬性時,我的麻煩就開始了。 像這樣的東西:
<a href="#" id="openReport" data-bind="onclick: $root.reportUrl()" >
Show report
在報告網址中,這是一個可觀察到的變量。 這是打字稿代碼:
export var reportUrl =<any> ko.observable();
export var expandRow = function (myObjectComeFromATable) {
var urlAction = '@Url.Action("Index", "Report", new { Id= ID_TO_REPLACE, languageId = LANG_TO_REPLACE }) ';
var url = "showReport('"+urlAction+"');";
reportUrl(url);
};
更新使用引號是可以的。 剔除變量的值與之前顯示的硬代碼值相同。 也許是我的布局存在問題?
您正在嘗試評估可觀察的代碼? 我認為這不會起作用。 您可以在函數中手動執行評估。 但是我認為這不是一個好的解決方案。
如果您總是在單擊時調用“ showReport”,則不需要評估:只需在模型中包含一個包含要調用的url的屬性,然后在回調函數中運行showReport(yourUrl)。
如果單擊時調用的函數發生更改,則可以保留對要在模型中調用的函數的引用。 像這樣(但更干凈):
var model = function() {
var _this = this;
this.function1 = function() {
alert('hello');
}
this.function2 = function() {
alert('world');
}
this.run = function() {
_this.current();
}
this.change = function() {
_this.current = _this.function2;
}
this.current = this.function1;
}
ko.applyBindings(new model());
<a href="#" data-bind="click: run">Click</a>
<a href="#" data-bind="click: change">Switch</a>
看到這里: http : //jsfiddle.net/pp2QA/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.