在 MVC 中使用 HTML 按钮
我觉得问这个问题有点愚蠢,但我只是想知道如何让 html 按钮调用我的控制器上的服务器站点操作。
例如,假设我有一个文本区域和一个提交按钮。这个想法是单击提交按钮,文本区域中的文本将被提交到数据库。非常简单的东西。
谢谢您的帮助!
I feel a bit stupid asking this, but I just want to know how I can have a html button call a server site action on my controller.
For example lets say I have a Text Area and a submit button. The idea would be to click the submit button and the text in the text area would get submitted to the Database. Very simple stuff.
Thank you for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 aspx 中:
在控制器中(本例中为 HomeController):
编辑:解决有关维护 URL 的其他问题
一种实现“保持原位”的方法URL 是“重载”控制器的 Index 方法,如下所示
然后在 Index.aspx 中更改 Html.Begin 表单,如下所示,您现在只需指向默认操作
因为您正在发布到控制器而不是获取(默认值) index 操作)设置为 AcceptVerb POST 并采用 userName 字符串的版本将运行,并且应维护您的 URL
in the aspx:
In the Controller (HomeController in this example):
EDIT: To address additional question about maintaining URL
One method to accomplish "staying in place" as far as your URL is to "overload" the Index method of your controller like below
Then in your Index.aspx change the Html.Begin Form like below, your just pointing to the default action now
Since you are posting to the controller and not getting(the default index action) the version that is setup to AcceptVerb POST and take the userName string will run and your URL should be maintained
在视图的 HTML 中,文本区域和提交按钮将是表单的一部分,并且该表单的
action
属性将指向''
并且您可以将一部分放入生成检查 POST 数据的视图的同一控制器。如果有 POST 数据,则将其写入数据库。表单看起来像这样:
在 POST 中,您将看到一个变量,其键与文本区域的
name
属性相匹配(在本例中为text
) 。您可以从那里阅读它。如果您愿意,还可以将表单上的
action
属性更改为 URL,在这种情况下,您可以编写用于检查该 URL 指向的控制器中的 POST 数据的部分。In the view's HTML, the text area and submit button would be part of a form, and that form's
action
attribute would point to''
and you'd put a part into the same controller that generated that view that checks for POST data. If there's POST data, you'd write it to the database.The form would look something like this:
In the POST, you'll see a variable with a key that matches the
name
attribute of the textarea (in this case,text
). You can read it from there.If you like, you can also change the
action
attribute on the form to a URL, in which case you'd write the part that checks the POST data in a controller that that URL points to.