[英]Setting a value to a HiddenField in ASP.NET 4.5
我在ASP.NET 4.5中為HiddenField設置值時遇到了一些問題。
從我所看到的,我已經嘗試了以下沒有任何運氣:
在ASPX中:
<asp:HiddenField ID="HiddenField" runat="server" value="" />
<script type="text/javascript">
function SetHiddenField() {
var vv = "HELLO WORLD";
document.getElementById('<%=HiddenField.ClientID%>').value = vv;
}
</script>
在代碼隱藏中:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('" + HiddenField.ClientID + "');", true);
這會在ClientID中警告垃圾。
我試過的另一個解決方案如下。
在.ASPX中:
<asp:HiddenField ID="HiddenField" runat="server" value="" />
<script type="text/javascript">
function SetHiddenField() {
var vv = "HELLO WORLD";
document.getElementById('HiddenField').value = vv;
}
</script>
這里的一個問題是,IntelliSense中不存在.value
,僅存在.ValueOf
。
在代碼隱藏中:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('" + HiddenField.Value + "');", true);
沒有任何事情發生,可能是JavaScript中的錯誤,因為沒有顯示警報。
有人能指出我正確的方向嗎?
你的第一個標記是好的:
<asp:HiddenField ID="HiddenField" runat="server" value="" />
<script type="text/javascript">
function SetHiddenField() {
var vv = "HELLO WORLD";
document.getElementById('<%=HiddenField.ClientID%>').value = vv;
}
</script>
將代碼更改為此(檢查第二行):
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert(document.getElementById('" + HiddenField.ClientID + "').value);", true);
輸出應該是這樣的:
編輯:在您的方案中,您可以運行javascript來獲取值並強制回發以使用代碼中的值。 我會將我的標記更改為:
<script type="text/javascript">
function SetHiddenField() {
var vv = "HELLO WORLD";
document.getElementById('<%=HiddenField.ClientID%>').value = vv;
__doPostBack('<%=HiddenField.ClientID%>', '')
}
</script>
在代碼中,我的Page_Load如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Register JavaScript which will collect the value and assign to HiddenField and trigger a postback
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true);
}
else
{
//Also, I would add other checking to make sure that this is posted back by our script
string ControlID = string.Empty;
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
ControlID = Request.Form["__EVENTTARGET"];
}
if (ControlID == HiddenField.ClientID)
{
//On postback do our operation
string myVal = HiddenField.Value;
//etc...
}
}
}
在隱藏字段標簽中添加clientid
靜態像這樣 -
<asp:HiddenField ID="HiddenField" runat="server" value="" ClientIDMode="Static" />
這樣,ASP.Net不會用動態ID替換它,並且總是擁有你提供的id,所以現在它將具有ID HiddenField
。 然后你的第二次嘗試應該工作。
更多信息可以在這里找到 -
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode(v=vs.110).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.