Jquery dynamic TextBoxes with Request.form Iteration - c#

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...
}
}

Related

How to insert data to details Table in mvc core using (Jquery) or (Jquery and Ajax)

old school c# developer here..
long story short, the company I'm working for has decided to continue developing using core technology and as a former winforms developer I'm not familiar with the web concepts and having trouble saving the details table to the master table. Any help is very appreciated.
I have two Tables with 1 to many Relationship
TOURNAMENTS_M (Master)
TOURNAMENTS_D (Detail)
I have edited the scaffolded Create page to include the fields for the detail table for entry.
I have even managed to update the table(visually) for the added details records using Jquery.
I'm having trouble to save this information to my database though, there have been a couple of different tutorials I've been following to with different approaches.. yet could't manage to succeed using neither approaches...
1st Approach is using Jquery and Ajax method. I've seen examples where people save data through a modal window and when save is clicked the data is updated on the gridview so as I understood(correct me if I'm wrong) Ajax is used to reload data without refreshing the page, and to postback the data to the controller. In my case I'm no sure if this is the right method to use since both master and child controls are on the same page.
2nd Approach is using just Jquery
in this approach my Create method in the controller and jquery methods are as following
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(TOURNAMENTS_M pTournamentsM)
{
if (ModelState.IsValid)
{
_context.Add(pTournamentsM);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(pTournamentsM);
}
function GetCurrentDetail() {
var TD_LEVEL = $("#TD_LEVEL").val();
var TD_SB = $("#TD_SB").val();
var TD_BB = $("#TD_BB").val();
var tourDetail = {
"TD_LEVEL": TD_LEVEL,
"TD_SB": TD_SB,
"TD_BB": TD_BB
};
return tourDetail;
}
//triggers when clicked on add tour details button
function CreateRowForTourDetails() {
var current = GetCurrentDetail();
var index = $("#detailsTable").children("tr").length;
var indexcell = "<td style='display:none'> <input type='hidden' id='index" + index + "' name='TOURNAMENTS_D.index' value = '" + index + "' /> </td>";
var TD_LEVEL = "<td> <input type='hidden' id='TD_LEVEL" + index + "' name='TOURNAMENTS_D[" + index + "].TD_LEVEL ' value = '" + current.TD_LEVEL + "' />" + current.TD_LEVEL + " </td>";
var TD_SB = "<td> <input type='hidden' id='TD_SB" + index + "' name='TOURNAMENTS_D[" + index + "].TD_SB ' value = '" + current.TD_SB + "' />" + current.TD_SB + " </td>";
var TD_BB = "<td> <input type='hidden' id='TD_BB" + index + "' name='TOURNAMENTS_D[" + index + "].TD_BB ' value = '" + current.TD_BB + "' />" + current.TD_BB + " </td>";
//var removeButton = "<td><a id ='myRemove' data-itemId='0' class='btn btn-primary'>Remove</a></td>";
var tourDetail = "<tr>" +indexcell + +TD_LEVEL + TD_SB + TD_BB + "</tr>";
var detailsTableBody = $("#DetailsTableBody");
detailsTableBody.append(tourDetail);
}
with this method when I place my break point inside the Create function in my controller I can see that the count of TOURNAMENTS_D increases however the value is null
Try Web Browser Debug tool to check the request, make sure your request like below:
Here is My Model:
public class Order
{
public int Id { get; set; }
public string OrderNo { get; set; }
public ICollection<OrderDetail> OrderDetails { get; set; }
}
public class OrderDetail
{
public int Id { get; set; }
public int ProductId { get; set; }
}

C# WebBrowser click submit button with no response

This is my first time asking questions on StackOverflow, and I will be as much specific as I can.
When I opened the website with my Chrome, Firefox and IE, the submit button 'upgrade' works fine after I selected a file to upload/upgrade to the server (my router).
But when I'm trying it on my C# Winform project using the "WebBrowser" component, the submit button doesn't response at all (after I selected the file) whether I'm manually clicking the button or writing C# code to trigger the onClick event.
Does anyone have a clue? Any help would really be appreciated, thanks!
P.S. I'm sorry I can't provide to much picture about the webpage because I'm currently working under a company.
This is the what the webpage looks like
The html code of the webpage is showed below:
<table>
<td>
<label class="subtt2" style="margin-bottom:8px;font-size:14px">
Software Image:
</label>
</td>
<td>
<div class="file-box">
<input id="firmware" name="fupgrade.bin" class="file"
onchange="getfileName()" type="file" style="cursor:pointer">
<input id="filename" class="txt" type="text">
<input class="btnWtn" value="Browse" type="button">
<label class="error" id="lupgradeforbidden" style="display: none"></label>
</div>
</td>
</table>
<div class="buttonStyle" align="left">
<input name="UPLOAD_ACTION" id="UPLOAD_ACTION" value="Upgrade"
onclick="upgradeRouter()" type="button">
</div>
The upgradeRouter() is as follows:
function upgradeRouter()
{
var FIRMWARE = document.getElementById( "firmware" );
var UPLOAD_ACTION = document.getElementById( "upload_action" );
if( FIRMWARE.value == "" )
alert( "Please select firmware file" );
else
{
fileSize = FIRMWARE.files.item(0).size;
if(fileSize > 0)
{
if( uploading == 0 )
{
document.forms["myForm"].submit();
setTimeout("firmware_update_query_request();", POLLING_FW_STATUS_SECONDS*1000);
document.getElementById('upgradeFrame').style.display = 'none';
document.getElementById('upgradeModalBox').style.display = 'block';
UPLOAD_ACTION.value = "Cancel";
uploading = 1;
}
else
{
uploading = 0;
UPLOAD_ACTION.value = "Update";
myForm.reset();
}
}
}
return false;
}
Since fileSize = FIRMWARE.files.item(0).size; crash (which leads to clicking the upgrade button with no repsonse), the work around solution to my problem is just to inject script into the web page and execute my version of upgradeRouter() again.
Which I set up the value of fileSize manually beforehand.
The injection code is shown below
public void InjectScript()
{
HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptElement.DomElement;
element.text = "function upgradeRouter_M()" +
"{ " +
"var FIRMWARE = document.getElementById(\"firmware\"); " +
"var UPLOAD_ACTION = document.getElementById(\"upload_action\");" +
" if (FIRMWARE.value == \"\")" +
" alert(\"Please select firmware file\");" +
" else" +
"{" +
"fileSize = 47599364;" +
"" +
"if (fileSize > 0)" +
"{" +
"if (uploading == 0)" +
"{" +
"document.forms[\"myForm\"].submit();" +
"setTimeout(\"firmware_update_query_request();\", POLLING_FW_STATUS_SECONDS * 1000);" +
"document.getElementById('upgradeFrame').style.display = 'none';" +
"document.getElementById('upgradeModalBox').style.display = 'block';" +
"UPLOAD_ACTION.value = \"Cancel\";" +
"uploading = 1;" +
"}" +
"else" +
"{" +
"uploading = 0;" +
"UPLOAD_ACTION.value = \"Update\";" +
"myForm.reset();" +
"}" +
"}" +
"}" +
"}";
headElement.AppendChild(scriptElement);
webBrowser1.Document.InvokeScript("upgradeRouter_M");
Console.WriteLine("Injection completed");
}

can not find dynamic html select in code behind

i have a class named "row" that has 3 item {property,instance,degree}.
now i want to show my items or rows to user and if he changed the third part of class i edit it. this is my code of generating rows dynamically, numberOfInstance is number of rows.
<div id="hidden" class="hiddendiv">
<%
string matn = "";
for (int i = 0; i < numberOfInstance ; i++)
{
row r= new row();
r = a[i];
matn+= " <div class='CMSdiv'>";
matn += "<input id='Text"+i+"' class='labelhid' type='text'"+"value = '"+r.Property+ "'/>";
matn += "<input id='Text2" + i + "' class='labelhid' type='text'" + "value = '" + r.instance+ "'/>";
matn += " <select id='Select" +i+ "'class='drophid' runat='server'>";
matn += " <option value= '"+ "خیلی زیاد"+"'>خیلی زیاد" + " <option value= '"+"زیاد'"+">زیاد";
matn += " <option value='"+"متوسط'"+">متوسط";
matn += " <option value='" + "کم'" + ">کم";
matn += "</select>";
matn += "</div>";
Response.Write(matn);
matn = "";
}
%>
</div>
now if user clicked on select and choose one option, i get it's value and pour to r.degree in code behind. but whatever i did i couldn't find it in code behind and was null. these are my attempts:
var val = Request["Select" + i];
string selection = Request.Form["Select" + i];
hd = (HiddenField)Page.FindControl("Select" + i);
hd = (HiddenField)Control.FindControl("Select" + i);
You can't generate server side controls by Response.Write (More info here). So html elements that you are writing to output are client side controls not server side and cannot be found using the Page.FindControl method.
Consider using one of the server side controls like Repeater instead.

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

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

Loop Button inside the Loop Div

I'm new here, I'm stuck in problem in which i have to loop my button so that i will be able to put it on my looping div. How will I do that? This is what I got so far:
//my loop
for (i = 0; i < MPreply.recommendation.Length; i++) {
html += "<div class='rec'> ";
html += "</br> <div id = 'from1' value = > Depart From:" + " ";
html += emz + " " + "(" + + ")" + "</div>";
html += "<div id = 'date1' > Schedule:" + " " + flytDate;
html += " , " + convertedString;
html += "</div>" + "<div id = 'to1' >To:" + " " + emz2 + " " + "(" + "" + ")";
html += "</div> </br> </br> </br> ";
html += "<div id = 'RecNo'>" + " " + (i + 1) + " )" + " </br> </br> </div> ";
html += "<div id = 'fare1'> $" + em + " </div> ";
html += " </div> <br/> <br/>";
div_rec.InnerHtml = html;
}
html:
<div id = 'modal' runat="server" >
<div id="dialog" runat="server">
</div>
<input id="_menuitem" type="button" value="Click" runat="server" />
</div>
Thanks in advance.
You have at least a few problems:
"<div id = 'fare1'>
and similar sections will generate multiple elements with the same id.
div_rec.InnerHtml = html;
Should be moved outside of your loop so that div_rec is only updated once, when everything is done.
emz + " " + "(" + + ")" + "</div>";
Should (probably) be changed to
emz + " " + "(" + your_variable_here + ")" + "</div>";
In order to (I think) add the creation of a button in your loop, you'll have to piece it together as a string just like your other elements. To get a function handler wired up you'll have to either:
a) Build a dom level-0 handler as a string, or
b) Wait until your html is updated, then query out the newly added buttons and add event handlers in code (using either btn.onclick = function(... or dom level-2 handlers (addEventListener or attachEvent)
The Problem i see here is with the ID field.
You have mentioned same ID name for all the Div's you are generating.
Like,
<div id = 'from1'>
<div id = 'to1'>
ID is a unique identifier to an element. It must always be unique.
You can Use Class instead.
Like,
<div class = 'from1'>
<div class = 'to1'>

Categories

Resources