编程按钮OnClick事件

本文关键字:事件 OnClick 按钮 编程 | 更新日期: 2023-09-27 18:15:43

我试图使一个方法运行一旦用户单击页面上的按钮。我创建了一个示例代码来测试它,但它不起作用,尽管这可能是因为我使用了MessageBox。

<input id="upload-button" type="button" ondblclick="@ModController.ShowBox("Message");" value="Upload"/><br />

这是我要调用的方法。

public static DialogResult ShowBox(string message)
{
   return MessageBox.Show(message);
}

我怎么能使这个功能正确的想法?

编程按钮OnClick事件

如果您的意图是传递消息给客户端并显示对话框,则可以这样做:

在你看来,添加以下内容:

@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。

你有几个选择:

  1. 为dblClick事件设置javascript事件,并在事件处理程序中向服务器执行AJAX请求

  2. 使用@ActionLink()和样式它看起来像一个按钮

如果您正在使用ASP。. NET中,有一些POST参数可以在发送到服务器之前设置,这将告诉ASP。. NET运行某个事件处理程序。但是,如果您使用的是ASP。. NET,我建议使用web表单而不是Razor。我从未将Razor与ASP一起使用过。. NET,但我不认为这两种技术结合得很好。