有没有办法如何跳出表单方法并返回具有更新元素的页面?

时间:2019-02-09 18:55:55

标签: c# asp.net

我在asp.net应用程序后面的代码中有几种方法。我想在执行过程中发生某些事情时将消息返回给Label中的用户,并停止执行。

代码只是我要实现的示例。

我已经尝试过:

Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Redirect("to same page");

示例:(我不想执行unzipFile方法。我想用更新的标签重新加载当前页面)

protected void btnUpload_Click(object sender, EventArgs e) {
    uploadFile(Server.MapPath("~/") + filename);
    unzipFile(string newFile); 
}

protected void uploadFile(string newFile) {

if (newFile != null)
{
Label.Text="This is not valid file!"
    //stop processing load file with updated label
}
if (newFile.ContentType != "application/x-zip-compressed") {
Label.Text="This is not valid file!"
   //stop processing load file with updated label
    }
}

1 个答案:

答案 0 :(得分:0)

请不要重定向。回发已经到当前页面,除非有任何提示,否则应呈现当前页面。考虑一个简单的情况:

protected void Page_Load(/.../)
{
    // set some values on the page
}

protected void btnClick(/.../)
{
    label1.Text = "This is a test";
}

在按钮单击处理程序中仅包含该代码,单击按钮后将重新加载当前页面,唯一可见的更改将是文本输出。

您的情况并没有什么不同。设置标签,不要重定向。例如:

if (newFile != null)
{
    Label.Text = "This is not valid file!";
}
else if (newFile.ContentType != "application/x-zip-compressed")
{
    Label.Text = "This is not valid file!";
}
else
{
    // process the file
    Response.Redirect("SomewhereElse.aspx");
}

无论如何构建逻辑,最终的目标是一旦遇到错误情况就不再进行任何处理,只允许事件处理程序完成并重新渲染页面即可。


注意:我想你的意思是== null,可以简化条件。考虑:

if (newFile == null || newFile.ContentType != "application/x-zip-compressed")
{
    Label.Text = "This is not valid file!";
}
else
{
    // process the file
    Response.Redirect("SomewhereElse.aspx");
}

如果您不想使用else,则可以使用return完成相同的操作:

if (newFile == null || newFile.ContentType != "application/x-zip-compressed")
{
    Label.Text = "This is not valid file!";
    return;
}

// process the file
Response.Redirect("SomewhereElse.aspx");