ASP.NET How to use Counter with '<%= - c#

I want to make a multiple upload, iam using some script from this forum.
the scripts is perfectly works, but when i merge it with my project.
javascript can't get the value of my element.
i found out the problem is because i have many ID PANEL in the page, i need to change to getElementByID('<%="FileUpdate.ClientID%>').value (the original : getElementByID("FileUpdate").value)
THE PROBLEM IS :
I have to use counter, ex: getElementByID('<%="txtFileUpdate' + counter + '%>').value but it FAIL.
the error says "too many characters in character literal" pointing to that line.
Please someone help, is there any solution for this problem ?
Here is the script
-----> Error " to many characters in character literal"
<script type="text/javascript" language="javascript">
var counter = 1;
function AddFileUpload() {
if (counter < 5) {
counter++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="FileUpload' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainers").appendChild(div);
}
else {
alert("Cannot attach more than 5 file");
}
}
function GetFile() {
var temp;
var error = "";
var stringx = "";
var exCounter = 1 ;
for (exCounter; exCounter <= counter; exCounter++) {
-----> stringx = document.getElementById('<%=FileUpload'+exCounter+'.ClientID%>').value;
if (stringx != "")
temp += stringx + "#;";
else
error += exCounter + ", ";
}
if (error != "") {
alert("Field " + error + " Still Empty");
return;
}
document.getElementById('<%=HiddenField1.ClientID%>').value = temp;
}

Try this:
getElementByID('FileUpdate<%=counter%>').value
or
getElementByID('<%=txtFileUpdate + counter.ToString()%>').value

Related

MVC 3 to MVC 4 Razor Compiler Error

I am getting a runtime error, saying that I am missing a closing paren. The error occurs on the line where I set emailText
This code works in MVC 3 but not MVC 4. I know the new Razor is more strict but syntactically this code still looks right. All parens match, etc.
Any ideas?
#if (Model.Counselors != null)
{
for (var i = 0; i < Model.Counselors.Count; i++)
{
string counselorDivId = "counselorname" + i.ToString();
string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + #counselorDivId + "\" data-attr-id=" + #Model.Counselors[i].Id + " style=\"float:right;\"></a>";
string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
}
}
Strangely, but I guess logically, nested "#" blow up MVC 4/Razor 2. By removing the nested "#" prefixes, the code was successfully parsed and executed
#if (Model.Counselors != null)
{
for (var i = 0; i < Model.Counselors.Count; i++)
{
string counselorDivId = "counselorname" + i.ToString();
string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + counselorDivId + "\" data-attr-id=" + Model.Counselors[i].Id + " style=\"float:right;\"></a>";
string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
}
}
try
#(if (Model.Counselors != null)
{
for (var i = 0; i < Model.Counselors.Count; i++)
{
string counselorDivId = "counselorname" + i.ToString();
string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + #counselorDivId + "\" data-attr-id=" + #Model.Counselors[i].Id + " style=\"float:right;\"></a>";
string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
}
})
It appears to be an issue with the last line that starts with "string emailText ...". For some reason razor does not like the less than sign in your ternary statement. When I switched it around to be a greater than sign, then it looks like it worked. I am not sure if this is a bug in razor or not.

Calculate duration of the memory game and send it to the database

I need to calculate a total duration of the memory game. At the moment I can count the clicks, but I need to figure out how long it takes to open all images in sec. How can I send it to the database? I've tried some code but with no luck. This is my first experience with JavaScript, so please forgive me if the answer is obvious. Thanks for any advice.
Update: #Pieter21 Unfortunately it didn't work. I got an error: String was not recognized as a valid DateTime. At the moment "Duration" is a Timestamp in my localDB.
Javascript :
<script>
var BoxOpened = "";
var ImageOpened = "";
var startTime = new Date().getTime();
var Counter = 0;
var ImageFound = 0;
var Source = "#memorybox";
var ImageSource = [
"Images/animals/cow.jpg",
"Images/animals/cow2.jpg",
"Images/animals/sheep.jpg",
"Images/food/lemon.jpg",
"Images/animals/elephant.jpg",
"Images/animals/giraffe.jpg",
"Images/food/banana.jpg",
"Images/animals/dog.jpg",
"Images/animals/horse.jpg",
"Images/animals/lion.jpg"
];
function RandomFunction(MaxValue, MinValue) {
return Math.round(Math.random() * (MaxValue - MinValue) + MinValue);
}
function ShuffleImages() {
var ImageAll = $(Source).children();
var ImageThis = $(Source + " div:first-child");
var ImageArr = new Array();
for (var i = 0; i < ImageAll.length; i++) {
ImageArr[i] = $("#" + ImageThis.attr("id") + " img").attr("src");
ImageThis = ImageThis.next();
}
ImageThis = $(Source + " div:first-child");
for (var z = 0; z < ImgageAll.length; z++) {
var RandomNumber = RandomFunction(0, ImgArr.length - 1);
$("#" + ImageThis.attr("id") + " img").attr("src", ImageArr[RandomNumber]);
ImageArr.splice(RandomNumber, 1);
ImageThis = ImageThis.next();
}
}
function ResetGame() {
ShuffleImages();
$(Source + " div img").hide();
$(Source + " div").css("visibility", "visible");
Counter = 0;
$("#success").remove();
$("#counter").html("" + Counter);
BoxOpened = "";
ImageOpened = "";
ImageFound = 0;
return false;
}
function OpenCard() {
var id = $(this).attr("id");
if ($("#" + id + " img").is(":hidden")) {
$(Source + " div").unbind("click", OpenCard);
$("#" + id + " img").slideDown('fast');
if (ImageOpened == "") {
BoxOpened = id;
ImageOpened = $("#" + id + " img").attr("src");
setTimeout(function () {
$(Source + " div").bind("click", OpenCard)
}, 300);
} else {
CurrentOpened = $("#" + id + " img").attr("src");
if (ImageOpened != CurrentOpened) {
setTimeout(function () {
$("#" + id + " img").slideUp('fast');
$("#" + BoxOpened + " img").slideUp('fast');
BoxOpened = "";
ImageOpened = "";
}, 400);
} else {
$("#" + id + " img").parent().css("visibility", "hidden");
$("#" + BoxOpened + " img").parent().css("visibility", "hidden");
ImageFound++;
BoxOpened = "";
ImageOpened = "";
}
setTimeout(function () {
$(Source + " div").bind("click", OpenCard)
}, 400);
}
Counter++;
$("#<%=HiddenField1.ClientID%>").val(Counter);
$("#counter").html("" + Counter);
if (ImageFound == ImageSource.length) {
$("#counter").prepend('<span id="success" runat="server">You Found All Pictues With </span>');
setTimeout(function () {
var endTime = new Date().getTime();
console.log("duration = " + (endTime - startTime));
}, 1500);
//$("#HiddenField2").html("" + (endTime - startTime));
//alert(endTime - startTime);
$("#<%=HiddenField2.ClientID%>").val(endTime - startTime);
}
}
}
$(function () {
for (var y = 1; y < 3 ; y++) {
$.each(ImageSource, function (i, val) {
$(Source).append("<div id=card" + y + i + "><img src=" + val + " />");
});
}
$(Source + " div").click(OpenCard);
ShuffleImages();
});
HTML :
<span id="Span1" class="button" runat="server">
<span id="counter" >0 </span>
Clicks </span>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
<span class="button">
<a onclick="ResetGame();">Reset</a>
</span>
<asp:Button ID="Save" runat="server" Text="Save" OnClick="Button1_Click" CssClass="button" />
C# :
SqlConnection connection = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int value = int.Parse(HiddenField1.Value);
DateTime time = Convert.ToDateTime(HiddenField2.Value);
connection = DatabaseConnectionSetup();
SqlCommand submitCommand;
try
{
submitCommand = new SqlCommand("ResultInsert", connection);
submitCommand.CommandType = CommandType.StoredProcedure;
submitCommand.Parameters.AddWithValue("#Duration", HiddenField2.Value);
submitCommand.Parameters.AddWithValue("#UserScore", HiddenField1.Value);
connection.Open();
submitCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
connection.Close();
}
}
private SqlConnection DatabaseConnectionSetup()
{
try
{
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["MonkeyClubConnectionString"];
if (connectionString != null)
{
connection = new SqlConnection(connectionString.ConnectionString);
}
}
catch (Exception ex)
{
}
return connection;
}
You are doing the game length calculations only on the client side.
I think you already show some intentions to store it in a "hidden field 2", but you don't follow through. Uncomment the field in ASP.NET, fill it with Javascipt in the javascript, and copy it in the C# codebehind.
You also have to make sure that what you store in the field can be recognized as a datetime in SQL.

json index checking and reaching values

var jsonAdim = [];
function openModal(index) {
$("#<%= hidInputSenaryoIndex.ClientID %>").val(index);
$("#senaryoAdimTable tbody").html("");
jsonAdim = $("#<%= hidInputSenaryoAdim.ClientID %>").val();
console.log(jsonAdim);
for (i = 0; i < jsonAdim.length; i++) {
console.log(jsonAdim[i]["Index"] + " -- " + index);
if (jsonAdim[i]["Index"] == index + "") {
var tr = "<tr><td>" + jsonAdim[i]["X"] + "</td><td>" + jsonAdim[i]["Y"] + "</td></tr>";
$("#senaryoAdimTable tbody").append(tr);
}
}
}
I get this to console >
[{"Index":"1","X":"0","Y":"a1"},{"Index":"1","X":"0","Y":"a2"}]
undefined -- 1
Question >
how can I reach this as json? > jsonAdim[i]["Index"]
Looks like what contained in jsonAdim is JSON string, try using JSON.parse to get the objects out the string as follows:
jsonAdimParsed = JSON.parse(jsonAdim);
check out how to use JSON.parse here

Jquery dynamic TextBoxes with Request.form Iteration

i am Adding multiple TextBoxes with Jquery in my Application, then in code behind file i want can access the values by Request.form[name]. I want o iterate these textboxes and read values of whatever Text is entered by the user, so i can store it in database.
any idea how can i save the value of these textboxes in Database,
i am working in asp.net 2.0
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<table><tr><td><input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ></td><td><input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ></td><td><input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ></td></tr></table>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
return false;
counter++;
});
});
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("textbox"))
{
string value = Request.Form[key];
//Do some stuff...
}
}

GetElementsByTagName returns no elements in WebBrowser Control

This is my code:
webBrowser1.ObjectForScripting = this;
string str =
"<html><head><script type=\"text/javascript\">" +
"var list = document.getElementsByTagName('abbr');" +
"len = list.length;" +
"for(i = 0;i < len;i++)" +
"{obj=list[i];obj.onclick=window.external.Test(this.id);}" +
"</script></head>" +
"<body>";
for (int i = 1000; i < 1100; i++)
{
str += "<abbr id=\'" + i.ToString() + "\'" +
">" + i.ToString() + " </abbr>";
}
str += "</body></html>";
webBrowser1.DocumentText = str;
Thanks
As you placed your script in the <head>, it gets executed before the contents of the <body> are fully loaded. There are two possibilities to avoid that problem: You could place the script before the ending </body>-Tag or you execute your script onload.
window.onload = function () {
// Insert code that depends on a loaded body here.
}

Categories

Resources