HiddenField.value is undefined in JS - c#

In my aspx markup I have the following defined:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="hidField" />
I have C# code as follows, which gives my hidden field a value:
hidField.value = check().ToString();
assume that check is a function which returns true, for simplicity.
I made JS code to do the following:
_myBool = $("#hidField");
alert(_myBool.value);
This alerts undefined.
For debugging purposes, I stepped through and saw that in C#, hidField.value is indeed true.
And I tried alerting _myBool.length which returned 1 and _myBool which returned [Object object] so Im not calling undefined on undefined.

Try this
_myBool = $("#hidField"); //my bool is a jQuery Object
alert(_myBool.val()); //can only get value with .val()
OR
_myBool = $("#hidField")[0]; //[0] gets the element in the object
alert(_myBool.value); //can use the javascript .value

Missing $ symbol..
var _myBool = $("#hidField");
alert(_myBool[0].value); // DOM Object
alert(_myBool.val() ); // jQuery Object
Also note the selector might Not work with runat="server" attribute as it prepends the content placeholder..
This is a better selector
var _myBool = $('[id*="hidField"]');

You forgot the dollarsign and also use the val() function
alert($("#hidField").val());

Make sure you are using the right ID:
_myBool = $("#<%= hidField.ClientID %>").val();
View your source when the page loads and check for that field. Chances are the ID is not "hidField". The code above will be correct.

Related

re-use parameter from html href in asp c#

I'm opening a new window to another .aspx page in which I pass a couple of parameters and I wanted to re-pass the parameter ID from the actual page:
<asp:Button ID="Button1" runat="server" CausesValidation="False" meta:resourceKey="btnAddRow2"
OnClientClick="window.open('SecondPage.aspx?type=Usuaris&id=SPECIALID', '_blank')" Text="Miau" />
As you can see, the type parameter works well but I don't have the slightest idea how to get the "specialID" from the current page which would be:
http://blablabla.com/FirstPage.aspx?SPECIALID=36
So i want to get that 36 (which is a dynamic number so I can't actually put a 36 directly over there) in order to open the second page as follows:
http://blablabla.com/SecondPage.aspx?type=Usuaris&SPECIALID=36
As I said at the beginning the user IS at he FirstPage.aspx and upon pressing a button will go to the SecondPage.aspx
hi you can change the OnClientClick to call a javascript function which will get the specialId and then call the window.open with the full string.
for example
function openWindow(){
var specialId = document.getElementById('someElement').value;
window.open('SecondPage.aspx?type=Usuaris&id=' + specialId, '_blank')"
}
I finally could do it doing the following in the FirstPage.aspx:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function AddUsuario() {
var id = getParameterByName("id");
window.open('SecondPage.aspx?type=Usuarios&id=' + id, '_blank');
location.reload();
}
On Page_Load() do following
Button1.Attributes.Add("onclick",
String.Format("window.open('SecondPage.aspx?type=Usuaris&id={0}', '_blank');",
Request.QueryString["SPECIALID"]));

Javascript Confirmation On if..else.. condition

I have to show confirmation dialogue on particular condition.And then proceed according to YES or No clicked.I tried with the following.
In aspx:
<script type="text/javascript">
function ShowConfirmation() {
if (confirm("Employee Introduced already.Continue?") == true) {
document.getElementById("hdn_empname").value = 1;
}
}
</script>
<asp:HiddenField ID="hdn_empname" runat="server" />
in cs:
if (reader2.HasRows)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "showAl", "ShowConfirmation();", true);
}
else
{
hdn_empname.Value ="1";
}
if ((hdn_empname.Value)=="1")
{
//some code to execute
}
But hdn_empname shows value="" while debuging.
Can anyone help me doing this?
Thanks in advance.
Try it
You need to ClientID
document.getElementById('<%=hdn_empname.ClientID%>').value = 1;
I found out your main problems
The hidden field values will assign after the if condition call.
Edit :
So, You need to call your logic's in javascript side using ajax
if (confirm("Employee Introduced already.Continue?") == true) {
//some code to execute
}
Where is your break point? If reader2.HasRows returns true your javascript will be registered. But it set the value on client and you get the result after postback.
hdn_empname is server controls Id which is different from client sided id, to get client sided id you need to use ClientID
try this:
document.getElementById('<%=hdn_empname.ClientID%>').value = "1";
You dont need to compare
if (confirm("Employee Introduced already.Continue?") == true)
this will work:
if (confirm("Employee Introduced already.Continue?"))

Using a C# list in a javascript snippet

I want to use two arrays from C# in the JS snippet in a view. In order to do so I've tried to use the JavaScriptSerializer() but the data array isn't getting any values (the view's source shows it as follows):
var mydata =
Every example I've come across injects the C# code in JS by using <%=%> tags. This doesn't yield any results for me since I'm using ASP.NET MVC 4. Therefore I tried it with the following:
<script type="text/javascript">
var mydata = #{ new JavaScriptSerializer().Serialize(Model.GetData());}
$(function () {
// Generates a chart using the mydata array
}
</script>
What's wrong about this syntax? When I try to add an array for the headers underneath it, I receive a compilation error. There are warnings that the lines aren't terminated, but when I add ; at the end of each line it gives a syntax error as well (no specific error, just 'syntax error').
The data in GetData() and GetHeaders() are defined as such:
public List<int> GetData() {
return new List<int>(new[] { 4, 5, 6});
}
I've tried returning it as a int[] but this made no difference.
How can I use a C# list/array in a JavaScript snippet?
Edit: image of the unknown compilation error.
When I don't place the semicolons I get a syntax error on the second var. I get a suggestion to terminate the line endings, which adds the semicolons to the end. Then I have the issue as shown below. Curious detail: there are no red bars to the side of the file that usually indicate where the error is located.
That being said: when executing the script, the arrays have their expected values and everything works as it should.
The problem is that #{ } creates a block of code, it doesn't print the result to the rendered page. You can do this:
#{
var serializer = new JavaScriptSerializer();
#serializer.Serialize(Model.GetData())
}
Or even better, use the Json helper:
#Json.Encode(Model.GetData())
When you enclose operations within code blocks the output won't be rendered unless you explicitly tells it to render.
Try this one:
#Html.Raw(Json.Encode(Model.GetData()))
Try to put the result of the serializer in single quotes, like:
<script type="text/javascript">
var data = '#{ new JavaScriptSerializer().Serialize(Model.GetData());}';
</script>
You can create a HTML helper to call this, example:
<script type="text/javascript">
var data = '#Html.JSSerializerHelper(Model.GetData())';
</script>
Only one way that I think most elegant.
You could convert your List into JavaScript array to use within js.
Try this:
<script type="text/javascript">
var mydata = [];
#foreach(int i in Model.GetData()) {
<text>mydata.push(#i);</text>
}
$(function () {
// Generates a chart using the mydata array
}
</script>

Microsoft JScript runtime error: 'null' is null or not an object

I have application like where i can create dynamic tabs. and delete cross bar option on tabs. When I am trying to delete the tab I am getting error like
Microsoft JScript runtime error: 'null' is null or not an object and point to my Javascript code.
Here is my JS code.
<script type="text/javascript">
/* <![CDATA[ */
function deleteTab(tabText)
{
var tabStrip = $find("<%= RadTabStrip1.ClientID %>");
var multiPage = $find("<%= RadMultiPage1.ClientID %>");
var tab = tabStrip.findTabByText(tabText);
var pageView = tab.get_pageView();
var tabToSelect = tab.get_nextTab();
if (!tabToSelect)
tabToSelect = tab.get_previousTab();
tabStrip.get_tabs().remove(tab);
multiPage.get_pageViews().remove(pageView);
if (tabToSelect)
tabToSelect.set_selected(true);
}
/* ]]> */
</script>
and in page lode
if (!Page.IsPostBack)
{
RadTab tab = new RadTab();
tab.Text = string.Format("New Page {0}", 1);
RadTabStrip1.Tabs.Add(tab);
RadPageView pageView = new RadPageView();
pageView.Height = new Unit("50px");
pageView.Width = new Unit("1300px");
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = 0;
}
This error can occur if you are trying to use an object which is null. In that code quite a lot of things can return null: $find, findTabByText, getPageView, get_nextTab, get_previousTab etc. I suggest you alert() everything before using it. That way you will find what is null.
You're not checking any of those function calls to see if they're actually returning something. One of them is returning null, but your code does not notice that and tries to use the result in a subsequent statement.
Try this in Firefox with Firebug and you'll probably get better error messages.
$find can return null if you are trying to call it too early. Remember that ASP.NET AJAX controls are created during the Sys.Application.Init event. If you try to access them earlier (e.g. in the window.onload) the $find() will not work.

how to pass session value from code behind to javascript

i have made a session variable Session["Background1"] = value; in one of my code behind function i want to retrieve this value in my javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
Personally, I prefer to do it the scripting way. Suppose your variable is currently declared in your Javascript as:
var background1 = null; // TODO: Add value from session.
To add the value from session, all you need to do is this:
var background1 = '<%= Session["Background1"] %>';
When the page is output by ASP.NET, the expression between <%= and %> is evaluated and written to the page, effectively becoming a Response.Write. As long as the member is available in your page at the public or protected level, you can push it into your Javascript it in this way.
I find this approach easier to work with than the obnoxiously verbose ClientScriptManager.

Categories

Resources