Accessing dynamic created html checkboxes in code behind - javascript

I am dynamically creating my html checkboxes at runtime using javascript/jquery like this. It's using the Jquery bootgrid.
isAssigned: function (column, row) {
if (row.isAssigned == "True" || row.isAssigned == "true") {
return "<input id='chk" + row.id + "' type='checkbox' name='chkMarks' checked='" + row.isAssigned + "' />";
}
else {
return "<input id='chk" + row.id + "' type='checkbox' name='chkMarks'/>";
}
}
What I need to do is somehow get the values in my submit buttons click event in the aspx.cs code behind. I cannot runat="server" these controls because the id is not added until after the page has loaded. I need to get the id's and whether they are true or false.
I was wondering if anyone knew the best approach for me to get these values in something like this.
protected void myTester_Click(object sender, EventArgs e)
{
var values = Request["chkMarks"].ToString();
}

You almost had it! You need to use Request.Form instead of just Request. That should give you access to all your DOM elements.
var values = Request.Form["chkMarks"].ToString();
Here is some more information on it: https://msdn.microsoft.com/en-us/library/system.web.httprequest.form(v=vs.110).aspx

Request.Unvalidated["chkMarks"]
can also be useful depending on what the value of this field is.

I did it using JSON in the end using a postback so not asynchronous which is hopefully useful to someone.
function BuildJSON() {
var jsonObj = [];
jQuery("input[name='chkMarks']").each(function () {
item = {}
item["id"] = this.id;
item["isAssigned"] = this.checked;
jsonObj.push(item);
});
var json = JSON.stringify(jsonObj);
$('#<%= hiddenMarksID.ClientID %>').val(json);
}
In the code behind I attached an event to button and picked up the JSON like so...
protected void btnSubmitMarks_Click(object sender, EventArgs e)
{
string json = hiddenMarksID.Value;
List<ChkMark> chkMark = new JavaScriptSerializer().Deserialize<List<ChkMark>>(json);
Here is the POCO...
public class ChkMark
{
public string id { get; set; }
public bool isAssigned { get; set; }
}

Related

Adding Hyperlinks to ValidationSummary using programatically added validators

I'm using the javascript from the answer in this question in a project of mine:
Adding Hyperlinks to ValidationSummary
It works really great. I've added it to the bottom of my masterpage (for some reason, even though it is inside $(document).ready, Page_Validators is null if i place it in the head section)
Anyway! I'm also adding some custom validators programatically on postback using this code:
public static CustomValidator ReturnErrorMessage(string message, string validationGroup, string controlToValidate = "")
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ErrorMessage = message;
control.ControlToValidate = controlToValidate;
return control;
}
However whenever I add a CustomValidator like that, in a button event, page_load or whatever, Page_Validators will be overridden and the errormessage will revert to the message without a anchor.
What gives? Am I doing something wrong or can someone explain what is happening?
I've tried debugging it and it does set the values correctly, but then it just reset afterwards.
I've tried for the heck of it and in $(document).ready set all validators as isvalid = false, and that gets overwritten too.
Im using asp.net 4.5 unobtrusive validation, but it does not make a difference if I turn it off.
Adding the javascript in code using Page.ClientScript.RegisterStartupScript at some point after the validator has been created does not work either.
If I don't add any validators in code everything works as expected.
I'm aware I can just add the anchor tags manually, but this is a lot of work to update existing validators instead of just tossing in a small script, so I'm hoping to get this to work.
You can use this code to test this:
using System;
using System.Web.UI.WebControls;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + txtName.ClientID;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = "errorGroup";
control.ErrorMessage = "Error message";
control.ControlToValidate = txtName.ClientID;
Form.Controls.Add(control);
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="vsSummary" runat="server" ValidationGroup="errorGroup" ForeColor="Red" HeaderText="Error!" />
</div>
</form>
<script>
$(document).ready(function() {
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function() {
//get target control and current error validation message from each validator
//[0] is needed when using aspnet 4.5 unobtrusive validation
var validator = $(this)[0];
var errorMsg = validator.errormessage;
var targetControl = validator.controltovalidate;
//make link only if theres a control to target
if (targetControl) {
var errorMsgWithLink = "<a href='#" + targetControl + "' style='color: #FF3232;'> " + errorMsg + "</a>";
//update error message with anchor tag
validator.errormessage = errorMsgWithLink;
}
});
});
</script>
</body>
</html>
If you want you can try implementing your own 'CustomValidationSummary' control by following the same design pattern as mentioned at Reference Source by Microsoft, and modify the render method to include anchor tag to wrap error text, before it is passed into the writer method at line number 462.
I ended up using a extension method, adding the anchor tag in the method
public static void AddValidator(this Page p, string message, string validationGroup, string controlToValidate = "", bool addAnchorTags = true)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ControlToValidate = controlToValidate;
if (addAnchorTags && !string.IsNullOrEmpty(controlToValidate))
{
control.ErrorMessage = "<a href='#" + controlToValidate + "' style='color: #FF3232;'> " + message + "</a>";
}
else
{
control.ErrorMessage = message;
}
p.Validators.Add(control);
}

JavaScript function in c# asp.net button click event not working

I'm in a asp.net c# project. I want to print employees card with bar code. So I write a html tag in string variable call htmlCon and it will bind a DIV tag in client side (get all employees and loop it for print one by one).
it work fine. but inside the htmlCon variable has java script function it will not run in loop.
protected void btnGenarate_ClickEvent(object sender, EventArgs e)
{
......
foreach (var item in empDetails)
{
htmlCon += ..........+
"<script>"+
"$(document).ready(function ()"+
"{ $('#barcode').JsBarcode('"+ item.EmployeeNo + "', { width: 1, height: 30 }); });"+
"</script>" +
"<img id='barcode' class='barcode'/>" +
"........................................"+
}
}
this code comes with bar code and it will print first round in the loop..I want to run all employees for get bar code.
You are generating many images with the same ID, you should generate a new id for each loop iteration. I would also recommend using a StringBuilder instead of a bunch of string concatenations:
protected void btnGenarate_ClickEvent(object sender, EventArgs e)
{
StringBuilder htmlCon = new StringBuilder();
for (int i = 0; i < empDetails.Count; i++)
{
htmlCon.AppendFormat("<script>$(document).ready(function () { $('#barcode{0}').JsBarcode('{1}', { width: 1, height: 30 }); });</script><img id='barcode{0}' class='barcode'/>",
i.ToString(), empDetails[i].EmployeeNo);
htmlCon.Append("........................................");
}
//To Use StringBuilder value
string html = htmlCon.ToString();
}

Append Hidden input fields and bind them to the Model

I'm usinge a 3rd Party file uploader(Backload)to upload images & JavaScript to get the uploaded image names.I want to bind that list of Image Names into my MVC model. My requirement is to create hidden inputs dynamically when I submit the form. I know , I have to use sequential binding here with a loop. Can anyone help me how to use proper syntax to achieve this.
It should be something similar to this
for (int i= 0; i< noOfImages; i++)
{
<input type="hidden" name="Model.Images[i].Name" value=file.name />
}
(please note that I don't want Ajax solution for this and please show me code to use in my Razor view or if there is another better solution please let me know).Thanks.
public class ItemModel
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<ImageModel> Images { get; set; }
}
public class ImageModel
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ItemModel Items { get; set; }
}
I use following JavaScript code to get the values of Uploaded File Name and to create hidden inputs when I click submit button of #ItemCreate form.
$('#ImageUplodedtable input[name="ImageName"]').each(function () {
$('#ItemCreateForm').append('<input name="ImageName" value="' + this.value + '"/>');
I'm adding the below part to my question. I missed single quotes and two plus signs ['+i+'] now it's working fine.
$('#ImageUplodedtable input[name="ImageName"]').each(function () {
for (int i= 0; i< noOfImages; i++)
{
<input type="hidden" name="Images[+'i'+].Name" value="' + this.value + '" />
}
I can't use .each() with for loop here.Can anyone suggest a way to get all the Image Names in Uploded table?
You've done it right in your for loop at the top, but once you get to the JavaScript portion, you're bungling the names. Keep the names of the input in the same style as the first for loop and you'll be fine, i.e. Images[N].Name where N is the index of the item in the collection.
I finally decided to use this function to create hidden files. I hope this may help a newbie like me in the future .
function CretaeHiddenFields(){
var uploadedImages = $('#ImageUplodedtable input[name="ImageName"]') ;
var divArea = $(#CreateInputDiv);
for (var i = 0; i < uploadedImages .length; i++) {
var imageName = document.createElement("input");
imageName.type = "hidden";
imageName.name = "Images[" + i + "].Name";
imageName.value = uploadedImage[i].value; // value of #ImageUplodedtable ImageNameinputs
formCreteItm.append(imageName);
}
}

After another page is loaded in a div, no control is working, giving error

I'm using div instead of iframe to call a page but as soon as the other page loads in div then after clicking on any button, or selecting radiobutton, these events give this error
This is how I load div
<script type="text/javascript">
$(function () {
setInterval(function () {
$('#result').load('frmChatRequest.aspx', function () {
});
}, 10000);
});
</script>
This is frmChatRequest.aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt_chatRequest = LookupChat.getPendingRequestInMyChat("",Int64.Parse(_objSession.LoginID), _objSession, _errMsg);
ClsDataBind.DoGridViewBind(gdvChatRequestRoom, dt_chatRequest, _errMsg);
myMarqueeChatRequest.InnerText = "You Have " + dt_chatRequest.Rows.Count.ToString() + " new chat request/s in your rooms in last 15 minutes";
}
}
protected void gdvChatRequestRoom_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
HiddenField hdn = ((HiddenField)gdvChatRequestRoom.Rows[0].Cells[0].FindControl("hdnAddPeople"));
string strHdnValue = hdn.Value;
//Button btn = ((Button)gdvChatRequestRoom.Rows[0].Cells[3].FindControl("btnAccept"));
//string strBtnID = btn.ID;
string strBtnID = e.CommandArgument.ToString();
string query = "select * from Q116 where Q116002="+strBtnID+ " and Q116001="+ hdn.Value ;
_objQ116.SelectAll(query);
_objQ116.Q116DF2 = _objSession.LoginID;
_objQ116.Update(_objQ116.Q116DF2);
_objQ116.SelectAll(query);
_objQ116.Q116004 = DateTime.Now.ToString("hh:mm:ss");
_objQ116.Update(_objQ116.Q116004);
//insert in Q119
// _objQ116.Update(Q116004);
//_objLOG2.SelectAll(query);
//DateTime dt1 = DateTime.UtcNow.AddHours(5.5);
//string str = dt1.ToString();
//_objLOG2.Update(str);
//Write code to add to card
}
if (e.CommandName == "Reject")
{
HiddenField hdn = ((HiddenField)gdvChatRequestRoom.Rows[0].Cells[0].FindControl("hdnAddPeople"));
string strHdnValue = hdn.Value;
//Button btn = ((Button)gdvChatRequestRoom.Rows[0].Cells[3].FindControl("btnAccept"));
//string strBtnID = btn.ID;
string strBtnID = e.CommandArgument.ToString();
string query = "delete from Q116 where Q116001=" + hdn.Value + " and Q116002=" + "'" + strBtnID + "'";
// _objQ116.SelectAll(query);
Educity.EduDB.Select(query);
//Write code to add to card
}
Response.Redirect(Request.Url.AbsolutePath);
}
The ASP.NET webforms JavaScript and markup is probably messing up the hosting page and this is why a whole page is normally loaded in an iframe.
Have you considered using custom controls? They are really easy and encapsulate functionality into objects that can be included in any web page. It looks like frmChatRequest would be better as a control. Building a custom control is very similar to building a aspx webforms page, but it can then be re-used.
For more info on custom controls see http://msdn.microsoft.com/en-us/library/zt27tfhy.ASPX

getElementByID() for web user control not working?

I have made a web user control (.ascx) which consists of the two html textbox and two input buttons, when I try to do document.getElementById('<%=ControlID.ClientID%>') it returns null. what could i have done wrong ?
source code:
<script language="javascript" type="text/javascript">
function intilize() {
var x = document.getElementById('<%=JSNumeric_Control.ClientID%>');
}
</script>
<table class="style1">
<tr>
<td >
<My:UserInfoBoxControl ID="JSNumeric_Control" runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<input id="Button1" type="button" value="button" onclick="intilize()" /><br />
</td>
</tr>
</table>
Here is the code for the Numbric.cs, the following are the property used and in page load i am using JavaScript to assign all the events for the HTML inputs:
public partial class NumricCounter : System.Web.UI.UserControl
{
public string defualtValue = "0";
public double defaultIncrementValue = 1;
public int defaultPrecsionValue = 0;
public string Button_Add_ClientID
{
get { return Button_Add.ClientID; }
}
public string Button_Subtract_ClientID
{
get { return Button_Subtract.ClientID; }
}
//Set and Get for all these properties. (Code Omitted)
public string Text;
public double IncrementValue;
public int PrecsionValue;
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Text_Output.Value = this.Text;
Button_Add.Attributes.Add("onclick", "Add(" + IncrementValue.ToString() + "," + PrecsionValue.ToString() + ");");
Button_Subtract.Attributes.Add("onclick", "Subtract(" + this.IncrementValue.ToString() + "," + this.PrecsionValue.ToString() + ")");
Text_Output.Attributes.Add("onkeyup", "check(" + this.PrecsionValue.ToString() + ");");
}
}
}
Try replacing your function:
function intilize() {
var x = document.getElementById('<%=JSNumeric_Control.ClientID%>');
}
with this:
function intilize() {
var x = document.getElementById('JSNumeric_Control');
}
The getElementById should read the ID of the element from the rendored html.
JSNumeric_Control.ClientID will return the ClientID of the control if it were rendered to the page. It's existance doesn't necessarily mean that there will be HTML on the final page that has that ID.
For example if you create a control that just outputs two buttons you will give each of those buttons different IDs that are not the same as the control that they live in. Often you might create a container div that you will put around all other content which you will give the ID of the Control to for easy finding but there is no reason for this to exist.
What you should do is either make sure that your control does create this HTML container with the ID of your control or you should refer specifically to the client ID of the items inside your control.
var button1 = document.getElementById('<%=JSNumeric_Control.Button1.ClientID%>');
The problem is that in the DOM there's no element with Id = ClientID of your UserInfoBoxControl. The controls inside your user control will have other Ids, like 'JSNumeric_Control_Button1', 'JSNumeric_Control_TextBox1' etc. If you need to get both of the input buttons, you can do one of the following:
Use jquery selector to find all inputs with type = button and id starting with <%=JSNumeric_Control.ClientID%>
Add two new properties to your control - FirstButtonClientID and SecondButtonClientID that will provide you with clientIDs of your buttons. Then you can use it in javascript.
Create custom javascript object which will represent your usercontrol and provide necessary functionality.
You are most likely trying to search the DOM before it's been loaded. Try putting your code inside an onload handler:
document.onload = function () {
alert(document.getElementById('<%=ControlID.ClientID%>'));
}
This makes sure that the code isn't executed before you actually have all of the DOM loaded.
//Button_Add is the control id inside the user control
var x = document.getElementByID(JSNumeric_Control.FindControl("Button_Add").ClientID);

Categories