c# - 在 C#/ASP.NET 中检测已提交的表单

标签 c# asp.net

我在同一网页上有两个表单,我想检测在发布事件时提交了哪一个表单,并根据提交的表单显示不同的消息。

我见过一些例子,人们根据单击的提交按钮检测到了这一点,但在我的例子中,只需按 Enter 键即可提交表单。是否可以根据表单名称/id 检测提交的是哪一个表单?如果无法做到这一点,最好的方法是什么?

这是我最简单形式的代码,我认为我使用的语法是在使用提交按钮时使用的,但我将其包含在内以防万一我错了:

<form method="post" name="form1" id="form1">
    <input type="text" name="textbox1" />
</form>

<form method="post" name="form2" id="form2">
    <input type="text" name="textbox2"  />
</form>

if(IsPost){
    if(Request["submit"] == "form1"){
        <p>Form 1 was submitted</p>
    }else if(Request["submit"] == "form2"){
        <p>Form 2 was submitted</p>
    }
}

最佳答案

您可以在每个表单中放置一个隐藏字段,其中包含表单的唯一名称:

<form method="post" name="form1" id="form1">
    <input type="text" name="textbox1" />
    <input type="hidden" name="Form1Submitted" value="true" />
</form>

<form method="post" name="form2" id="form2">
    <input type="text" name="textbox2"  />
    <input type="hidden" name="Form2Submitted" value="true" />
</form>

然后你可以在代码隐藏中检查它,如下所示:

if(IsPost){
    if(Request["Form1Submitted"] == "true"){
        <p>Form 1 was submitted</p>
    }else if(Request["Form2Submitted"] == "true"){
        <p>Form 2 was submitted</p>
    }
}

关于c# - 在 C#/ASP.NET 中检测已提交的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21429295/

相关文章:

c# - DataContract 序列化 - 基类、继承和覆盖

asp.net - 如何使用 ASP.NET MVC 项目启动 Azure 模拟器

c# - 错误 : VS2017 Live Unit Testing - only minus's - doesn't work

c# - 如何以编程方式创建 Google 帐户?

c# - 如何防止访问者篡改POST Action 中的id字段?

javascript - 如何设置滚动条移动到多行文本框中的最后一行?

c# - JQUERY AJAX 多个级联dropdownlist select不加载问题

c# - 如何使用先前输入的参数重新加载页面?

c# - 移植 C# 代码。这是对全局对象的引用吗?

c# - 如何在按钮上单击弹出窗口,该按钮位于 uwp 中另一个弹出窗口中的位置