如何创建一个从 httpget 获取相同参数的 httppost?
我有一个控制器来显示模型(用户),并且想要创建一个仅带有激活按钮的屏幕。我不需要表单中的字段。我已经在 url 中获得了 id。我怎样才能做到这一点?
I have a controller to show up a model (User) and want to create a screen just with a button to activate. I don't want fields in the form. I already have the id in the url. How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 [ActionName] 属性 - 这样您可以让 URL 看似指向同一位置,但根据 HTTP 方法执行不同的操作:
或者您可以在代码中检查 HTTP 方法:
Use [ActionName] attribute - this way you can have the URLs seemingly point to the same location but perform different actions depending on the HTTP method:
Alternatively you can check the HTTP method in code:
在这方面有点晚了,但我发现了一个更简单的解决方案,可以解决我认为相当常见的用例,在该用例中,您提示 GET(“您确定要blah blah blah吗?” ),然后使用相同的参数对 POST 进行操作。
解决方案:使用可选参数。不需要任何隐藏字段等。
注意:我只在 MVC3 中测试过这一点。
最后一点,您不能使用 string.Empty 代替
""
因为它必须是编译时常量。这是一个放置有趣评论供其他人查找的好地方:)A bit late to the party on this but I found an easier solution to what I think is a fairly common use-case where you prompt on GET ("are you sure you want to blah blah blah?") and then act on POST using the same argument(s).
The solution: use optional parameters. No need for any hidden fields and such.
Note: I only tested this in MVC3.
On a final note, you can't use string.Empty in place of
""
because it must be a compile-time constant. And it's a great place to put funny comments for someone else to find :)您可以在表单内使用隐藏字段:
或将其传递到表单的操作中:
You could use a hidden field inside the form:
or pass it in the action of the form:
我的方法是不添加未使用的参数,因为这似乎会引起混乱,并且通常是不好的做法。相反,我所做的是将“Post”附加到我的操作名称中:
My approach is not to add an unused parameter as that seems like it would cause confusion, and is in general bad practice. Instead, what I do is append "Post" to my action name:
对于这种简单情况,最简单的方法是给提交按钮命名并检查它是否有价值。
如果它有值,则它是 Post 操作,如果没有,则它是 Get 操作:
对于 C,您可以将 get 和 post 控制器方法合并为一个:
The easiest way for such simple situation is to give a name to submit button and check in action if it has value or not.
If it has the value, then it Post action, if not, then it Get action :
For Cs you can combine get and post controller methods in one: