簡體   English   中英

使用mvc2和c#,如何從視圖中調用控制器中的void方法

[英]Using mvc2 and c#, how do I call a void method in my controller from view

我試圖在html中創建一個按鈕,當單擊該按鈕時,它將調用控制器中的一個方法,該方法將創建pdf。

我的控制器是DashboardController,我的方法叫做PrintConfirm()

這是我的HTML:

<a onclick="<%:Url.Action("PrintConfirm")/%>fileName" rel="external" target="_blank">
    <button class="ui-icon ui-icon-print" data-role ="button">Print Confirmation</button>
</a>

當我運行它時,我得到的只是一個打印機圖標,而當我單擊它時什么也沒有發生

您的gator標簽不正確,您的onclick應該是href 嘗試這個:

<a href='<%=Url.Action("PrintConfirm")%>/filename' rel="external" target="_blank">
    <button class="ui-icon ui-icon-print" data-role ="button">Print Confirmation</button
</a>

此外,您不能從視圖中調用void方法。 只能調用操作,並且操作必須具有ActionResult的返回類型。

另外,如果您的PrintConfirm操作與返回當前視圖的控制器PrintConfirm同一控制器上,則還需要指定該控制器的名稱。

<%=Url.Action("PrintConfirm", "PdfPrinter") /* where the controller is PdfPrinterController */%> 

編輯

如果您只是嘗試異步調用該動作,則可能要使用jQuery和AJAX。 讓我知道您是否想舉個例子。

首先應將Onclick替換為href

Onclick是可以由JavaScript代碼處理的事件,因此在您的情況下,它不會執行任何操作,因為Onclick將包含操作的相對URL而不是js代碼。 但您也不必使用它,只需使用常規href屬性。

查看生成的代碼。 您會看到類似

<a onclick="/Dashboard/PrintConfirmfilename" rel="external" target="_blank">

我對嗎? onclick需要使用javascript。

讓我們一起解決這個問題...

Url.Action()返回什么? 網址。

<a>標記可用於1)將用戶導航到URL(在這種情況下,您使用hre =屬性)和/或2)運行一些javascript(在這種情況下,您將javascript函數的名稱放在onclick屬性)。

您在此處所做的是將一個URL放在onclick中,但這根本不起作用。

我唯一知道的方法是使用AJAX

 $.ajax({ type: "GET",
        url: "./PrintConfirm",
        success: function (data) {
            //Load your PDF in the appropriate div? here
        }
    });

否則,您必須致電控制器並適當地重新加載屏幕。

Url.Action將返回指向控制器中動作的URL。 這樣,您最終將得到如下結果:

<a onclick="/myController/PrintConfirmfilename" rel="external" target="_blank">...

這里有兩個問題:

  1. 該操作的正確URL可能是/ myController / PrintConfirm,而不是/ myController / PrintConfirmfilename。 多余的“文件名”似乎很奇怪。

  2. 在標簽中包含HTML按鈕標簽似乎很奇怪。 我建議選擇一個。

假設/ myController / PrintConfirm實際上指向生成所需PDF的動作,則有一些選擇:

<a href=<%:Url.Action("PrintConfirm")>>
   Print Confirmation
</a>

要么

<button onclick=window.location=<%:Url.Action("PrintConfirm")>
   Print Confirmation
</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM