[英]Programming Button OnClick Event
我試圖在用戶點擊頁面上的按鈕后運行方法。 我創建了一個代碼示例來測試它,但它不起作用,但可能是因為我正在使用MessageBox。
<input id="upload-button" type="button" ondblclick="@ModController.ShowBox("Message");" value="Upload"/><br />
這是我正在調用的方法。
public static DialogResult ShowBox(string message)
{
return MessageBox.Show(message);
}
關於如何正確使用此功能的任何想法?
如果您的意圖是將消息傳遞給客戶端並顯示一個對話框,您可以執行以下操作:
在您的視圖中,添加以下內容:
@using (Html.BeginForm("ShowBox","Home",FormMethod.Post, new { enctype = "multipart/form-data" })){
@Html.Hidden("message", "Your file has uploaded successfully.");
<input id="upload-button" type="submit" value="Click Me" />
<input id="file" name="file" type="file" value="Browse"/>
}
然后在你的控制器中:
[HttpPost]
public ActionResult ShowBox(string message, HttpPostedFileBase file)
{
if (file == null || file.ContentLength == 0)
{
//override the message sent from the view
message = "You did not specify a valid file to upload";
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"));
file.SaveAs(path);
}
System.Text.StringBuilder response = new System.Text.StringBuilder();
response.Append("<script language='javascript' type='text/javascript'>");
response.Append(string.Format(" alert('{0}');", message));
response.Append(" var uploader = document.getElementById('upload-button'); ");
response.Append(" window.location.href = '/Home/Index/';");
response.Append("</script>");
return Content(response.ToString());
}
注意:我認為這種方法不太理想。 我很確定從控制器直接返回這樣的JavaScript可能是某種反模式。 至少,它感覺不對,即使認為它工作得很好。
看起來你正在使用Razor模板。 如果是這樣,並且你正在使用MVC,我認為你沒有接近這個權利。 MVC不適用於像ASP.NET這樣的事件系統。 在MVC中,您需要對ACtion方法進行請求,通常使用{controller} / {action}形式的URL,或類似的東西。
你有幾個選擇:
為dblClick事件設置javascript事件,並在事件處理程序中對服務器執行AJAX請求。
使用@ActionLink()並將其設置為看起來像一個按鈕。
如果您使用的是ASP.NET,則可以在發布到服務器之前設置某些POST參數,這將告訴ASP.NET運行某個事件處理程序。 但是,如果您使用的是ASP.NET,我建議您使用Web表單而不是Razor。 我自己從未使用過Razor和ASP.NET,但我認為這兩種技術並不是很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.