asp.net-mvc ASP.NET MVC - IsPostBack 还在吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/777179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC - Is IsPostBack still here?
提问by chief7
I know, I know, I know. I shouldn't be doing webforms inside of MVC, I completely agree. But, the people who sign my paycheck will not approve a complete conversion of our site to MVC right now. So I am taking incremental steps, page by page, to convert them over while adding new features in MVC.
我知道,我知道,我知道。我不应该在 MVC 内部做 webforms,我完全同意。但是,签署我的薪水的人现在不会批准将我们的网站完全转换为 MVC。因此,我正在逐页采取增量步骤来转换它们,同时在 MVC 中添加新功能。
So my question is how can I access the IsPostBack property from a controller?
所以我的问题是如何从控制器访问 IsPostBack 属性?
Edit:To further clarify, I have a webform user control on my mvc master page which can initiate postbacks. I'm trying to identify these postbacks verses an mvc post. At this point I think I am going to just check the request form keys for a "__viewstate" key and if its found treat it as a postback.
编辑:为了进一步澄清,我的 mvc 母版页上有一个 webform 用户控件,可以启动回发。我正在尝试通过 mvc 帖子识别这些回发。在这一点上,我想我将只检查“__viewstate”键的请求表单键,如果找到它,则将其视为回发。
回答by Nuri
In case anyone is still interested, you can test for a POST from inside an MVC Action Method like this:
如果有人仍然感兴趣,您可以像这样从 MVC 操作方法内部测试 POST:
if (Request.HttpMethod=="POST") {
}
回答by tvanfosson
There is no IsPostBack -- everything is either a POST or GET (or other HTTP verb). You can limit the HTTP verbs that your action allows, i.e., you'll never see a request from a disallowed verb, using the AcceptVerbsAttribute. For example, the following only allows POSTs.
没有 IsPostBack——一切都是 POST 或 GET(或其他 HTTP 动词)。您可以使用 AcceptVerbsAttribute 限制您的操作允许的 HTTP 动词,即,您永远不会看到来自不允许的动词的请求。例如,以下仅允许 POST。
[AcceptVerbs( HttpVerbs.Post )]
[ValidateAntiForgeryToken]
public ActionResult Update( int id )
{
}
If you need to have the same action name do both GET/POST and they actually do different things, you can either give them separate signatures or use the ActionNameAttribute to alias one of the actions so the methods can have different names.
如果您需要在 GET/POST 中使用相同的操作名称并且它们实际上执行不同的操作,您可以为它们提供单独的签名或使用 ActionNameAttribute 为其中一个操作设置别名,以便方法可以具有不同的名称。
[AcceptVerbs( HttpVerbs.Get)]
public ActionResult List()
{
}
[AcceptVerbs( HttpVerbs.Post )]
[ValidateAntiForgeryToken]
public ActionResult List( string filter, int page, int limit )
{
}
OR
或者
[ActionName( "List" )]
[AcceptVerbs( HttpVerbs.Get)]
public ActionResult ListDisplay()
{
}
[AcceptVerbs( HttpVerbs.Post )]
[ValidateAntiForgeryToken]
public ActionResult List()
{
}
EDIT: Note that I've added the antiforgery token validation to the POST actions. You really should be using this to protect against cross-site scripting attacks.
编辑:请注意,我已将防伪令牌验证添加到 POST 操作中。您确实应该使用它来防止跨站点脚本攻击。
回答by ASP.Net Developer
You can use this piece of code in Razor
你可以在 Razor 中使用这段代码
@if(IsPost)
{
//dosomething
}
else
{
//do some other thing
}
回答by ibirite
I often use this Method (declared on my BaseController class)
我经常使用这个方法(在我的 BaseController 类中声明)
protected bool IsPostBack()
{
bool isPost = string.Compare(Request.HttpMethod, "POST",
StringComparison.CurrentCultureIgnoreCase) == 0;
if (Request.UrlReferrer == null) return false;
bool isSameUrl = string.Compare(Request.Url.AbsolutePath,
Request.UrlReferrer.AbsolutePath,
StringComparison.CurrentCultureIgnoreCase) == 0;
return isPost && isSameUrl;
}
回答by Chad Ruppert
Controllers do not inherit from System.Web.UI.Page. There is no isPostback property.
控制器不继承自 System.Web.UI.Page。没有 isPostback 属性。
回答by acromm
For Asp.net Core 2.x you could create an extension method on HttpRequest. Based on @ibirite answer could be something like this:
对于 Asp.net Core 2.x,您可以在HttpRequest上创建扩展方法。基于@ibirite 的答案可能是这样的:
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
namespace MyApp
{
public static class HttpRequestExtensions
{
public static bool IsPostBack(this HttpRequest request)
{
var currentUrl = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path, request.QueryString);
var referrer = request.Headers["Referer"].FirstOrDefault();
bool isPost = string.Compare(request.Method, "POST",
StringComparison.CurrentCultureIgnoreCase) == 0;
if (referrer == null) return false;
bool isSameUrl = string.Compare(currentUrl,
referrer,
StringComparison.CurrentCultureIgnoreCase) == 0;
return isPost && isSameUrl;
}
}
}
回答by rguerreiro
The MVC framework doesn't support the classic postback and viewstate used in the Web forms. So, no, you don't have access to the IsPostBack.
MVC 框架不支持 Web 表单中使用的经典回发和视图状态。所以,不,您无权访问 IsPostBack。
My advice to you is to have two branches: one with the current site where you're adding patches for known errors and another one where you build a new site from scratch. New features should be implemented in this one. I assume that most of your codebase is re-usable in the new site.
我给你的建议是有两个分支:一个是当前站点,你在其中添加已知错误的补丁,另一个是你从头开始构建一个新站点。应在此实现新功能。我假设您的大部分代码库都可以在新站点中重用。
When the new site is ready, put it in production.
新站点准备就绪后,将其投入生产。
回答by Jaime Enrique Espinosa Reyes
If you have more than one form in an MVC page, you can add a hidden input within the form with a meaningful ID and test if it has a value. This way you do not need to have two separate handlers (one for get and one for post).
如果您在 MVC 页面中有多个表单,您可以在表单中添加一个具有有意义 ID 的隐藏输入并测试它是否具有值。这样你就不需要有两个单独的处理程序(一个用于获取,一个用于发布)。
So inf the page and inside the form:
所以在页面和表单内部:
<input type="hidden" id="testForm" name="testForm" value="1"/>
And in the controller :
在控制器中:
if (Request.Form["testForm"] != null)
{
// ACTIONS FOR THE POSTED FORM
}
Hope it helps!
希望能帮助到你!
回答by Luis Abreu
Why are you trying to get that value from within a controller? Not sure if this will help you, but you can still use the traditional Request object to get info that was submitted by a form...
为什么要尝试从控制器中获取该值?不确定这是否对您有帮助,但您仍然可以使用传统的 Request 对象来获取表单提交的信息...
回答by Nate
I'm not sure if I understood your question correctly, but on the controller you would have an action that handles the initial GET from the browser and a second action to handle POSTs.
我不确定我是否正确理解了您的问题,但是在控制器上,您将有一个处理来自浏览器的初始 GET 的操作和处理 POST 的第二个操作。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyModel model)
{...}
public ActionResult Create()
{...}

