没有在javascript中获取hiddenfield值



我在获取隐藏字段值时遇到问题,该值是在代码后面的页面加载中设置的。问题是,当我试图在javascript中获取该集合值时,它给出了未定义或null。无法获取在代码隐藏的页面加载中设置的值。

//cs code is like this
protected async void Page_Load(object sender, EventArgs e)
{
HiddenField_alt_edit.Value = "[{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>addAlternativeRowWithData();</script>");
}
//aspx page declaration goes like this. Also i am using a master page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:HiddenField ID="HiddenField_alt_edit" runat="server"  Value="i am on."/>
</asp:Content>
// javascript file code goes like this
function addAlternativeRowWithData(mode) 
{
alert("test");
var idvalue = $("#HiddenField_alt_edit").val();
alert(idvalue);
alert($nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val());
var myHidden = document.getElementById('<%= HiddenField_alt_edit.ClientID %>').value;
alert(myHidden);
var json_string = $nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val();
var arr_from_json = JSON.parse(json_string);
alert("test 2");
alert(arr_from_json);
}

客户端生成的id可能会有所不同,因为在设置runat="server"时,隐藏字段是代码中的服务器端控件。

通常有两种方式。要么使ClientIDMode为静态,要么使用表单中的实例来获取客户端id。

类似:

<asp:HiddenField ID="HiddenField_alt_edit" ClientIDMode="static" runat="server"  
Value="i am on."/>

然后以下应该起作用:

var idvalue = $("#HiddenField_alt_edit.ClientID").val();

或者在客户端代码中,你需要获得如下id:

var idvalue = $("#<%= HiddenField_alt_edit.ClientID %>").val();

更改:
HiddenField_alt_edit.Value = [{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]

对此:
HiddenField_alt_edit.Value = " [{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]"

然后,添加以下内容:
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on." ClientIDMode="Static" />

在你的js中,你必须放这个:

const value = document.getElementById('HiddenField_alt_edit').value
const jsonString = JSON.stringify(value)
const json = JSON.parse(jsonString)
console.log(json)
<input hidden id="HiddenField_alt_edit" value="[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]">

最新更新