我写了一个很长的asp.net webform,它有大约44个控件。并且此数据将保存到数据库中。我的问题是,在表单提交后,我想清除ViewState中的所有数据,并且应该清除webform控件的内容。如果不手动(并且繁琐地)清除每个控件,怎么可能呢?
ViewState.Clear()
不起作用
Page.EnableViewState = false
不起作用。
答案 0 :(得分:3)
插入完成后,只需使用Response.Redirect
从头开始重新加载同一页面。
例如Page.Response.Redirect(Page.Request.RawUrl)
答案 1 :(得分:3)
如果你停留在同一个页面上,在客户端清除它或从回发中的代码隐藏中进行清除会比重定向稍微好一些,因为你要保存到服务器的行程,尽管它需要更多的工作。
此外,Response.Redirect(url)
会引发ThreadAbortionException
,这会对效果产生负面影响,因此,如果您想转到重定向路线,请考虑Response.Redirect(url, false)
。
客户端选项:(简单方法)
<script>
$(':input').each(function () {
switch (this.type) {
case 'password':
case 'text':
case 'select-multiple':
case 'select-one':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
break;
}
});
</script>
代码来自this post。
服务器端选项:
您可以遍历所有控件以清除它们。在处理表单的函数结束时,添加:
ClearForm(Page.Form.Controls);
功能:
public void ClearForm(ControlCollection controls)
{
foreach (Control c in controls)
{
if (c.GetType() == typeof(System.Web.UI.WebControls.TextBox))
{
System.Web.UI.WebControls.TextBox t = (System.Web.UI.WebControls.TextBox)c;
t.Text = String.Empty;
}
//... test for other controls in your forms DDL, checkboxes, etc.
if (c.Controls.Count > 0) ClearForm(c.Controls);
}
}
通过控件和子控件循环会出现很多问题,因此您可以编写扩展方法来执行此操作。类似于what I did in this post的东西(而是一个函数,而不是返回所有控件的集合)。我在我的项目中有一个扩展方法来执行此操作,称为GetAllChildren(),因此上面的相同代码将执行如下:
foreach (Control i in Page.Form.GetAllChildren())
{
if (i.GetType() == typeof(System.Web.UI.WebControls.TextBox))
{
System.Web.UI.WebControls.TextBox t = (System.Web.UI.WebControls.TextBox)i;
t.Text = String.Empty;
}
// check other types
}
答案 2 :(得分:1)
试试这个
public static void ClearFields(ControlCollection pageControls)
{
foreach (Control contl in pageControls)
{
string strCntName = (contl.GetType()).Name;
switch (strCntName)
{
case "TextBox":
TextBox tbSource = (TextBox)contl;
tbSource.Text = "";
break;
case "RadioButtonList":
RadioButtonList rblSource = (RadioButtonList)contl;
rblSource.SelectedIndex = -1;
break;
case "DropDownList":
DropDownList ddlSource = (DropDownList)contl;
ddlSource.SelectedIndex = -1;
break;
case "ListBox":
ListBox lbsource = (ListBox)contl;
lbsource.SelectedIndex = -1;
break;
}
ClearFields(contl.Controls);
}
}
protected void btn_cancel_Click(object sender, EventArgs e)
{
ClearFields(Form.Controls);
}
答案 3 :(得分:0)
我建议您不要使用ViewState。它旨在正确匹配控件的状态。
相反,只需通过重定向或明确清除控件来更改控件的状态。
答案 4 :(得分:0)
抱歉,由于声誉不佳,我无法为Omkar Hendre的回答添加评论。 代码很好,对于我的问题,我需要在Form.Controls之前放置Page。
ClearFields(Page.Form.Controls);
顺便说一句,非常感谢! :)