Jquery dynamic TextBoxes with Request.form Iteration and Save to DB - 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 to 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 spliting each textbox values by a Comma(,)
Please guide me how to get all these textbox values in loop and then save them in DB Table
$(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++;
});

Probably you have do something like this, you could easily debug by using chrome debugger tool to retrieve all values from your input boxes.
$('table tr td').each(function() {
var values = "";
values = $(this).find('input').val() + ",";
});

Related

populating HTML Radio buttons from code behind in C#

I am generating radio buttons from Code Behind in the following code
var licRB = questions[QNo - 1].AnswerRadioButton.optionRB;
for (int i = 0; i < licRB.Length; i++)
{
if (licRB[i]._checked == "true")
{
stringBuilder.Append(String.Format("<input type=\"radio\" name=\"Q" + (QNo) + "AnswerRBOption\" value='{0}' title='{1}' checked=\"checked\" />{1} <br />", licRB[i].value, licRB[i].text));
}
else
{
stringBuilder.Append(String.Format("<input type=\"radio\" name=\"Q" + (QNo) + "AnswerRBOption\" value='{0}' title='{1}' />{1} <br />", licRB[i].value, licRB[i].text));
}
}
(FindControl("divQ" + QNo + "AnswerRBL") as HtmlGenericControl).InnerHtml = stringBuilder.ToString();
On submit button click the value selected is stored in the db as follows:
ARBValue = Request.Form["Q" + QNo + "AnswerRBOption"],
Now I need to retrieve the value from the DB and show the radio buttons with the selected value. Pls let me know best way to do this?
Below text resolves the issue of showing the selected radio button in the HTML5 radio button list
(FindControl("divQ" + q.QNo + "AnswerRBL") as HtmlGenericControl).InnerHtml = q.ARBOption
.Replace("checked=\"checked\"","")
.Replace("value='"+ q.ARBValue + "'" , "value='" + q.ARBValue + "' checked=\"checked\"");

Why 'innerhtml' does not work properly for 'select' tag

I am trying to set the innerhtml of an html select tag but I cannot set this feature;therefor,I need to use the outerhtml feature.This way,not only is my code HARDCODE ,but also it is preposterous.I have already read 'InnerHTML IE 8 doesn't work properly? Resetting form',it did not help though.
I would really appreciate it if you tell me how to set the innerhtml feature of an html select tag.
My C# code:
public void SetDefaultValue(string ControlID, string ControlValue)
{
System.Windows.Forms.HtmlDocument doc = webBrowser1.Document;
HtmlElement HTMLControl = doc.GetElementById(ControlID);
string ListResult;
string ListInnerHTML = "";
ListInnerHTML += "<OPTION value = " + LstString + ">" + LstString + "</OPTION>";
ListResult = "<SELECT id = " + '"' + HTMLControl.Id + '"' + " type = " + '"' + HTMLControl.GetAttribute("type") + '"' + " title = " + '"' +
HTMLControl.GetAttribute("title") + '"' + " name = " + '"' + HTMLControl.Name + '"' + " value = " + '"' + HTMLControl.GetAttribute("value") +
'"' + " size = \"" + HTMLControl.GetAttribute("size") + '"' + HTMLControl.GetAttribute("multiple").ToString() + "\">" + ListInnerHTML + "</SELECT>";
HTMLControl.OuterHtml = ListResult;
}
or
string _lsthtml = _htmlel.OuterHtml;
string[] _parts = ControlValue.Split(new char[] { ',' });
string _lstinner = "";
foreach (string _lst in _parts)
_lstinner += "<option value=" + _lst + ">" + _lst + "</option>";
_lsthtml = _lsthtml.Insert(_lsthtml.IndexOf(">") + 1, _lstinner);
_htmlel.OuterHtml = _lsthtml;
This code works but I need something efficient and clean.
The ReturnControlType function returns the type of an html tag.
This is an official Internet Explorer bug:
BUG: Internet Explorer Fails to Set the innerHTML Property of the Select Object.
One workaround
You may try adding one of the following meta tags in your document's head:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
or
<meta http-equiv="X-UA-Compatible" content="IE=10" />
You should also properly format the option tag's value attribute (enclose LstString in '):
ListInnerHTML += "<OPTION value='" + LstString + "'>" + LstString + "</OPTION>";
A more reliable solution
As the fixes above might be a workaround for your code, I would suggest to use a more reliable approach. Consider adding a reference to Microsoft.mshtml to your project and modifying your method like this:
// add this to the top of the file containing your class
using mshtml;
public void SetDefaultValue(string ControlID, string ControlValue)
{
System.Windows.Forms.HtmlDocument doc = webBrowser1.Document;
IHTMLDocument2 document = doc.DomDocument as IHTMLDocument2;
var sel = doc.GetElementById(ControlID);
HTMLSelectElement domSelect = (HTMLSelectElement)sel.DomElement;
domSelect.options.length = 0;
HTMLOptionElement option;
// here you can dynamically add the options to the select element
for (int i = 0; i < 10; i++)
{
option = (HTMLOptionElement)document.createElement("option");
option.text = String.Format("text{0}", i);
option.value = String.Format("value{0}", i);
domSelect.options.add(option, 0);
}
}
I really don't know why innerHTML is not working for you.
If it just dosen't you could try an alternative:
http://innerdom.sourceforge.net/
demo
In this thread it is sugested you use the items collection of a control
How to add items to dynamically created select (html) Control
refer to this page for a complete example:
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlselect.items.aspx

How to retrieve an annotation in web resource and display it using popup window - crm 2011

How to show annotation present in an entity in popup window by using html web resource. My requirement is to display annotation present in an entity in a popup window and in popup window user should be able to delete , upload and convert the annotation to pdf (if he wants). Can you suggest a best method to achieve this in crm 2011.
function retann() {
//debugger;
var serverUrl = Xrm.Page.context.getServerUrl();
var GUIDvalue = Xrm.Page.data.entity.getId();
// Creating the Odata Endpoint
var oDataPath = "http://url/organization/XRMServices/2011/OrganizationData.svc/";
var retrieveReq = new XMLHttpRequest();
var Odata = oDataPath + "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + GUIDvalue + "'";
retrieveReq.open("GET", Odata, false);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };
retrieveReq.send();
}
function retrieveReqCallBack(retrieveReq) {
if (retrieveReq.readyState == 4 /* complete */) {
//debugger;
var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
var message = "";
var fun_var =
"<script type=text/javascript>" +
"function result_value()" +
"{" +
"var rad_val;" +
"for (var i=0; i < document.orderform.test.length; ++i){if (document.orderform.test[i].checked){rad_val = document.orderform.test[i].value;}}" +
"if(rad_val==null || rad_val=='')" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue('0');" +
"}" +
"else" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue(rad_val);" +
"}" +
" window.top.opener.Xrm.Page.data.entity.attributes.get('new_fireplugin').setValue(1);" +
"window.top.opener.Xrm.Page.data.entity.save();" +
"this.window.close();" +
"}" +
"function result_value1()" +
"{" +
"var rad_val1;" +
"for (var i=0; i < document.orderform.test.length; ++i){if (document.orderform.test[i].checked){rad_val1 = document.orderform.test[i].value;}}" +
"if(rad_val1==null || rad_val1=='')" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue('0');" +
"}" +
"else" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue(rad_val1);" +
"}" +
" window.top.opener.Xrm.Page.data.entity.attributes.get('new_delete').setValue(1);" +
"window.top.opener.Xrm.Page.data.entity.save();" +
"this.window.close();" +
"}" +
"</script>";
var n = retrieved.results.length;
for (var i = 0; i < retrieved.results.length; i++) {
message += " <input type='radio' name='test' value=' " + i + "' />" + retrieved.results[i].FileName + "<br />";
}
myWindow = window.open('', '', 'width=500,height=150,left=250,top=250,scrollbars=yes,resizable=yes,directories=yes');
myWindow.document.write(fun_var + "<body bgcolor=GhostWhite style='font-family:verdana;font-size:11px;'><form name='orderform' style='font-family:verdana;font-size:11px;'>" + message + "</br><center ><input type='button' onclick='result_value()' style='font-family:verdana;font-size:11px;' value='Convert To PDF'/></center>" + "</form>");
myWindow.focus();
}
}
function SetField() {
var AddressType = Xrm.Page.data.entity.attributes.get("new_radiovalue");
AddressType.setValue("");
}
function save_form() {
// var MainPhone = Xrm.Page.data.entity.attributes.get("new_name").getValue();
//Xrm.Page.data.entity.attributes.get("new_name").setValue(MainPhone+".");
Xrm.Page.data.entity.save();
}
retrieveReqCallBack(this) function displays the popup with annoatation. Using the above code i'm able to convert doc to pdf. Since i want to add multiple functionalities like upload , delete and convert to pdf. If annotation is present then popup should have option to upload and if annotation is present then it has to show delete and convert to pdf buttons.
I found this as solution to my question,
You'll need to create a custom web resource (html) with javascript to pull the data out of the sub-grid, parse the rows, query the crm data via REST or SOAP to see if there is an annotation, then put an icon of the 'paperclip' which'll allow users to upload attachments against that record.

Dynamically insert checkbox into a table in ASP.NET with variable number of fields. C# codebehind

I'm building an exemption request form that populates from an SQL Server 2008 database.
DataRow[] exemption = ds.Tables[2].Select();
foreach (DataRow dr in exemption)
{
string exemptionType = dr["ExemptionType"].ToString();
string exemptionID = dr["ExemptionID"].ToString();
string exemptionDesc = dr["ExemptionDescription"].ToString();
string displayLabel = dr["DisplayLabel"].ToString();
sb.Append("<table align='center' width='730px'>");
sb.Append("<tr><td><asp:CheckBox ID=\"chk" + exemptionID + "\" runat=\"server\" /></td>");
sb.Append("<td><strong>" + exemptionDesc + "</strong></td>");
sb.Append("</table>");
sb.Append("<table align='center' width='630px'>");
sb.Append("<tr><td>" + displayLabel + "</td></tr>");
sb.Append("</table>");
}
return sb.ToString();
As it stands right now, the table builds fine, all the data displays fine, but the checkbox does not show up. Was wondering if doing it this way is possible at all, and if so, what am I doing wrong?
You're inserting ASP.NET into your HTML and that HTML is probably not getting processed by ASP.NET. If you want to do it the way you're doing it now... switch to using input tags like so...
DataRow[] exemption = ds.Tables[2].Select();
foreach (DataRow dr in exemption)
{
string exemptionType = dr["ExemptionType"].ToString();
string exemptionID = dr["ExemptionID"].ToString();
string exemptionDesc = dr["ExemptionDescription"].ToString();
string displayLabel = dr["DisplayLabel"].ToString();
sb.Append("<table align='center' width='730px'>");
sb.Append("<tr><td><input type=\"checkbox\" id=\"chk" + exemptionID + "\" /></td>");
sb.Append("<td><strong>" + exemptionDesc + "</strong></td>");
sb.Append("</table>");
sb.Append("<table align='center' width='630px'>");
sb.Append("<tr><td>" + displayLabel + "</td></tr>");
sb.Append("</table>");
}
return sb.ToString();
The other route would be to actually create the ASP.NET Checkboxes. That would look somethig like this...
var checkbox = new CheckBox();
checkbox.ID = "chk" + exemptionId;
wrapper.Controls.Add(checkbox);
Where wrapper is a Panel or something of the sort.

Creating jquery object array and posting its values on form submit

I have dynamicly added html elements(selectlists) in a form :
//Dynamicly adding selectlist elements
function newshit() {
i = i + 1
$("#mytable").append("<tr><td><div id='div" + i + "'><select id='elem" + i + "' name='elem" + i + "' class='ted'></select><input type='button' value='-' id='buttonminus" + i + "' style='width:5%;' onclick='removeelem(elem" + i + ",buttonminus" + i + "," + i + ")'/></div></td></tr>")
getitems("elem" + i)
}
//filling lists
function getitems(item) {
$.getJSON('#Url.Content("~/Stok/Items/")', {}, function (data) {
$.each(data, function (i, c) {
$("#" + item).append("<option value='" + c.Value + "' title='" + c.Text + "' label='" + c.Text + "'>" + c.Text + "</option>")
})
})
}
//removing element, when button next to it used
function removeelem(elem,buttonminus,i) {
if ($("select").length > 1) {
$("#div" + i).closest('tr').empty().remove()
} else if ($("select").length <= 1) {
alert("At least 1 of items must be chosen to create a group!")
}
}
//checking elements and values existence
function check() {
var slcts = $("select").serialize();
alert(slcts)
}
im trying to get the value of each selectlist's selected option value and put them into an array than send them to my controller on form submit.
How can i achive this?
Need to check this, but I think that the following should work:
Change your code so that the format of your ids is something like:
id="elem[0]"
Then if your controller has a signature something like this:
public ActionResult Something(IEnumerable<string> elem)
{
}
Then his should "just work".
You could use something like -
var selectdata = $("select").serialize()
This will return a string in the form <select name attribute1>=<chosen value1>&<select name attribute2>=<chosen value2> etc. You'd need to add a 'name' attribute to your select HTML when you create it for this to work.
Demo - http://jsfiddle.net/ipr101/fZXha/
You could then put the selectdata variable in a hidden field before the form was posted or send it via AJAX using the ajax or post methods.

Categories