asp.net MVC 3 中的多个按钮单击
我的 asp.net mvc 3 页面上有多个动态按钮。在 asp.net mvc 3 中处理按钮单击的最佳方法是什么? ASP.NET 中没有事件处理,那么处理的最佳实践是什么?
I am having multiple dynamic buttons on my asp.net mvc 3 page. what is the best way to handle button click in asp.net mvc 3? there is no event handling in asp.net, so what is the best practice to hadle.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 javascript 通过订阅按钮的单击事件来处理按钮的单击。例如,使用 jQuery,您可以为这些按钮指定一个类,然后:
或者如果这些是表单的提交按钮,您可以为它们指定相同的名称和不同的值,然后在服务器上测试名称参数的值。它的值将等于被单击的按钮。
例如,假设您有以下带有多个提交按钮的表单:
现在,在您要发布到的控制器操作中,您可以确定单击了哪个按钮:
You could handle the buttons clicks using javascript by subscribing to their click event. For example with jQuery you could give those buttons a class and then:
or if those are submit buttons of a form you could give them the same name and different values and then on the server test the value of the name parameter. It's value will equal to the button that was clicked.
Let's suppose for example that you have the following form with multiple submit buttons:
Now inside the controller action you are posting to you could determine which button was clicked:
如果按钮不需要相同的表单数据,那么您可以创建两个具有不同操作方法的表单。这是最简单的解决方案。
如果您需要使用相同的表单数据,那么有多种方法,包括 Darin 和 tvanfosson 的方法。还有一种基于属性的方法,它将根据单击的按钮选择正确的操作方法。
http://www.dotnetcurry.com/ShowArticle.aspx?ID=724
If the buttons do not require the same form data, then you can create two forms with different action methods. This is the easiest solution.
If you need to use the same form data, then there are a number of methods, inclduing Darin and tvanfosson's approaches. There is also an approach based on attributes that will select the correct action method based on which button is clicked.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=724
取决于按钮的作用。如果它们在逻辑上是独立的操作,那么您可以将每个回发到服务器端的单独操作。这通常也有效,它们是同一操作的变体,“保存”与“取消”,例如,“保存”发回表单,“取消”重定向到您之前的 URL(例如,返回编辑的详细信息)。如果按钮代表将被发送回同一操作的不同数据,则可以为它们指定不同的值。如果按钮被命名,则值将与表单的其余部分一起发回(假设它们包含在表单中)。如果从 AJAX 发回,您可能需要显式序列化按钮值以及表单。
保存/取消示例
然后使用 CSS,也许结合 jQuery UI 来设置按钮的样式。
Depends on what the buttons are doing. If they are logically separate actions, then you could have each postback to a separate action on the server side. This often also works they are variants of the same action, Save vs. Cancel, for instance where Save posts back the form and Cancel redirects to you the previous url (say, going back to details from edit). If the buttons represent different data that would get posted back to the same action, you can give them different values. If the buttons are named, the values will get posted back along with the rest of the form, assuming they are included in the form. If posting back from AJAX, you might need to explicitly serialize the button value along with the form.
Example of Save/Cancel
Then use CSS, perhaps in conjunction with jQuery UI to style the buttons.