I have javascript function return array like this:
<script type="text/javascript">
function looping() {
var column_num = 1;
var array = [];
$("#columns ul").not("#column1").each(function() {
var ulId = $(this).attr("id");
var ulClass = $(this).attr("class");
if (ulId != undefined && ulClass != undefined) {
var order = -1;
column_num++;
$("li", $(this)).each(function() {
var liId = $(this).attr("id");
var liClass = $(this).attr("class");
if (liId != undefined && liClass != undefined) {
order++;
var result = liId + "|" + liClass + "|" + column_num + "|" + order;
array.push(result);
//alert(array[0]);
}
});
}
});
return array;
}
</script>
How can I retrieve the result in another array in my code behind .cs in button click event?
The only way i see is send result using POST or GET AJAX request.
$.get("/server/page.aspx", { looping: looping() });
On ServerSide do:
var array = Request.Params["looping"];
Store the array in a hidden field <input type="hidden" name="hidfld" id="hidfld" /> inside your form.
document.getElementById("hidfld").value = array;
On the serverside, use the hidden field's name to retrieve the array
Related
I'm using an external file where I get company data. The autocomplete works just fine, inputs get filled. But when I save the page into my database all the autocompleted fields don't get bind.
public Save(saveorder: Boolean): void {
let order: Order = ko.toJS(OrderPage.Instance().Order);
let date = OrderPage.Instance().Order.DateAccepted;
let removefromorderlines: Array<number> = [];
OrderPage.Instance().j$.each(order.OrderLines, (index: number, orderline: OrderLine) => {
// Check if there are any orderlines that don't have a modelid
if (orderline.ArticleModelId == null) {
removefromorderlines.push(index);
}
});
let previousindex: any = 0;
$.each(removefromorderlines, (index: number, orderlineindex: number) => {
order.OrderLines.splice(orderlineindex - previousindex, 1);
previousindex++;
});
if (saveorder == true) {
OrderPage.Instance().ToggleDisableButton('btnSaveOrder', true);
webApi.Execute(HttpRequestType.Post, '/Order/SaveOrder', order, OrderPage.Instance().OnSaveSuccess, OrderPage.Instance().OnSaveError);
}
The data that is missing is inside of 'Order'. The data gets picked up as soon as I change anything about the inputs. I've tried to use "valueUpdate: 'input'" but no success so far.
This is my autocomplete code:
namespace Services {
interface kvkResult {
handelsnaam: string;
dossiernummer: number;
straat: string;
huisnummer: number;
huisnummertoevoeging: string;
postcode: string;
plaats: string;
ModelId: string;
displayname: string;
ContactPersonModelId: string;
}
interface Contact {
ModelId: string;
displayname: string;
}
export class kvkFactory
{
private ctlCompanyName: string;
private ctlContainerName: string;
private ctlCoc: string;
private ctlAddress: string;
private ctlAddressNumber: string;
private ctlAddressNumberSuffix: string;
private ctlZipCode: string;
private ctlTown: string;
private ctlModelId: string;
private ctlContactPersonModelId: string;
/** Function to Fetch data from kvk api
#ctlSearch: Input control for coc organisations
#ctlAutocompleteContainer: output control to display organisations result.
#ctlCocClass: output text control for Kamer voor koophandel nummer
#ctlAddressClass: output text control for address organisation
#ctlZipCodeClass: output text contorl for zip code organisation
#ctlTownClass: output text contorl for town of settlement organisation
*/
constructor(ctlSearch: string, ctlAutocompleteContainer: string, ctlCompanyNameElement: string, ctlCocElement: string, ctlAddressElement: string, ctlAddressNumberElement: string, ctlAddressNumberSuffixElement: string, ctlZipCodeElement: string, ctlTownElement: string, ctlModelIdElement?: string, ctlContactPersonModelIdElement?: string, webapiurlforsearch?: string)
{
this.ctlCompanyName = ctlSearch;
this.ctlContainerName = ctlAutocompleteContainer;
this.ctlCompanyName = ctlCompanyNameElement;
this.ctlCoc = ctlCocElement;
this.ctlAddress = ctlAddressElement;
this.ctlAddressNumber = ctlAddressNumberElement;
this.ctlAddressNumberSuffix = ctlAddressNumberSuffixElement;
this.ctlZipCode = ctlZipCodeElement;
this.ctlTown = ctlTownElement;
this.ctlModelId = ctlModelIdElement;
this.ctlContactPersonModelId = ctlContactPersonModelIdElement;
$(this.ctlCompanyName).keyup(function () {
clearTimeout(this.typingTimer);
this.typingTimer = setTimeout(() => { kvkfactory.searchKvk(webapiurlforsearch); }, this.doneTypingInterval);
});
}
typingTimer: number;
datafound = (data: any): void =>
{
let resultobject: ResultObject<kvkResult> = data;
let companies = resultobject.Records;
$(kvkfactory.ctlContainerName).empty();
$(kvkfactory.ctlContainerName).show();
$(kvkfactory.ctlContainerName).append('<table>');
$.each(companies, function (i, item) {
let entry: kvkResult = item;
$('table', kvkfactory.ctlContainerName).append("<tr class=\"auto-complete-item\" data-modelid=\"" + entry.ModelId + " \" data-contactpersonmodelid=\"" + entry.ContactPersonModelId +" \"data-id=\"" + i + "\"><td>" + entry.handelsnaam + "</td><td>" + entry.straat + " " + entry.huisnummer + "</td><td>" + entry.postcode + "</td><td>" + entry.plaats + "</td></tr>");
});
$(kvkfactory.ctlContainerName).append('</table>');
$(".auto-complete-item").on("click", function () {
let id: string = $(this).data("id");
let contactidnumber = 1;
let contactid: string = $(this).data('contactidnumber');
let modelid: string = $(this).data("modelid");
let contacts = companies[contactidnumber];
let organisationmodelid: string[] = null;
let count: number = 0;
let company: kvkResult = companies[id];
if (kvkfactory.ctlModelId != undefined && modelid!=null ) {
$(kvkfactory.ctlModelId).val(modelid);
$(kvkfactory.ctlContactPersonModelId).val(organisationmodelid);
}
$(kvkfactory.ctlCompanyName).val(company.handelsnaam);
$(kvkfactory.ctlCoc).val(company.dossiernummer);
$(kvkfactory.ctlAddress).val(company.straat);
$(kvkfactory.ctlAddressNumber).val(company.huisnummer);
$(kvkfactory.ctlAddressNumberSuffix).val(company.huisnummertoevoeging);
$(kvkfactory.ctlZipCode).val(company.postcode);
$(kvkfactory.ctlTown).val(company.plaats);
$(kvkfactory.ctlModelId).val(company.ModelId);
$(".auto-complete-container").hide();
Materialize.updateTextFields();
});
$(document).mouseup(function (e) {
let container = $(".auto-complete-container");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
};
doneTypingInterval: number = 800;
searchKvk = (webapiurlforsearch?: string): void => {
if ($(this.ctlCompanyName).val().length >= 3) {
if (webapiurlforsearch == undefined) {
webapiurlforsearch = variables.websiteurl + "/Kvk/Getdata";
}
let val = $(this.ctlCompanyName).val();
webApi.Execute(HttpRequestType.Get, webapiurlforsearch, { name: val }, this.datafound, null);
} else {
$(".auto-complete-container").empty();
}
}
}
}
let kvkfactory: Services.kvkFactory;
I had a form in which I made some textboxes using javascript. Basically I gave a button and Onclick of that button I add a Textbox using Javascript.
These values were then taken in a string on the server side and stored in different List columns.
Now I want to create Edit Functionality. So I have to retrieve values from the List COlumns and Insert it in the Textboxes.
This was easy when my controls were server controls but How can I do this for textboxes that were created using Javascript.
I am new to client side scripting. Any help will be appreciated.
All I need is a way to get the values from the List COlumn and then create those textboxes again with those values.
PS: Please advise if you wana see the code for how I have created the textboxes and got those values on the server side.
Thanks!
Javascript Code to create Textboxes:
<script type="text/javascript">
function GetDynamicTextBoxB(value)
{ return '<input name = "DynamicTextBoxB" type="text" value = "' + value + '" />' + '<input type="button" value="Remove" onclick = "RemoveTextBoxB(this)" />' }
var y = 0;
function AddTextBoxB() {
if (y < 10) {
var div = document.createElement('DIV'); div.innerHTML = GetDynamicTextBoxB(""); document.getElementById("TextBoxContainerB").appendChild(div);
}
else {
alert("Only 10 CSPs can be added")
} y++
}
function RemoveTextBoxB(div)
{ document.getElementById("TextBoxContainerB").removeChild(div.parentNode); }
function RecreateDynamicTextboxesB() {
var values = eval('<%#Values%>');
if (values != null) {
var html = ""; for (var i = 0; i < values.length; i++)
{ html += "<div>" + GetDynamicTextBoxB(values[i]) + "</div>"; } document.getElementById("TextBoxContainerB").innerHTML = html;
}
}
$("#tabs-1").ready(RecreateDynamicTextboxesB);
// // window.onload = RecreateDynamicTextboxesB;
</script>
Code Behind to Get these values on the server side and storing in List COlumns
string PartyACSP1 = string.Empty, PartyACSP2 = string.Empty, PartyACSP3 = string.Empty, PartyACSP4 = string.Empty, PartyACSP5 = string.Empty, PartyACSP6 = string.Empty, PartyACSP7 = string.Empty, PartyACSP8 = string.Empty, PartyACSP9 = string.Empty, PartyACSP10 = string.Empty;
if (textboxValues != null)
{
PartyACSP1 = safeGetString(textboxValues, 0);
PartyACSP2 = safeGetString(textboxValues, 1);
PartyACSP3 = safeGetString(textboxValues, 2);
PartyACSP4 = safeGetString(textboxValues, 3);
PartyACSP5 = safeGetString(textboxValues, 4);
PartyACSP6 = safeGetString(textboxValues, 5);
PartyACSP7 = safeGetString(textboxValues, 6);
PartyACSP8 = safeGetString(textboxValues, 7);
PartyACSP9 = safeGetString(textboxValues, 8);
PartyACSP10 = safeGetString(textboxValues, 9);
}
newISDAAgreement[Constants.PartyACSPColumn] = PartyACSP1;
newISDAAgreement[Constants.PartyACSP2Column] = PartyACSP2;
newISDAAgreement[Constants.PartyACSP3Column] = PartyACSP3;
newISDAAgreement[Constants.PartyACSP4Column] = PartyACSP4;
newISDAAgreement[Constants.PartyACSP5Column] = PartyACSP5;
newISDAAgreement[Constants.PartyACSP6Column] = PartyACSP6;
newISDAAgreement[Constants.PartyACSP7Column] = PartyACSP7;
newISDAAgreement[Constants.PartyACSP8Column] = PartyACSP8;
newISDAAgreement[Constants.PartyACSP9Column] = PartyACSP9;
newISDAAgreement[Constants.PartyACSP10Column] = PartyACSP10;
while retrieving data from list column you must have a map of the data for which you want to create an edit functionality. for e.g.
suppose you have the data
listcolumn = {'data1': 123, 'data2': 234, 'data3': 345}
so just you can loop into that data and create the textboxes with its value in it.
for(key in listcolumn){
create a textbox and its value from listcolumn[key] (this will give you the value for that particular textbox)
}
or if are not comfortable with the dictionary thing
you can use the either way i.e. data is list form
listcolumn = [123,234,345]
for(data in listcolumn){
create a textbox and insert value in it.
}
but i would be preffered that you use JSON format from server side to front end
and you can parse the data using JSON.parse(data). And will get the dictionary as an object.
I would suggest to use a different architecture:
knockout.js - for a client-sisde, where you could develop your MVVM,
MVC - as the app type,
Ajax to send the queries to the server side for your ops like Loading,Saving, etc.
I use the AsyncUpload
<telerik:RadAsyncUpload runat="server" ID="rada_attach" OnClientFileUploaded="onClientFileUploaded"
MultipleFileSelection="Disabled" InitialFileInputsCount="1" MaxFileInputsCount="1"
Width="100%" />
function onClientFileUploaded(radAsyncUpload, args) {
var row = args.get_row(),
inputName = radAsyncUpload.getAdditionalFieldID("TextBox"),
inputType = "text",
inputID = inputName,
input = createInput(inputType, inputID, inputName),
label = createLabel(inputID),
br = document.createElement("br");
row.appendChild(br);
row.appendChild(input);
row.appendChild(label);
}
function createInput(inputType, inputID, inputName) {
var input = document.createElement("input");
input.setAttribute("type", inputType);
input.setAttribute("id", inputID);
input.setAttribute("name", inputName);
return input;
}
I want to access the textbox (which created dynamically) in .cs.
How to do that ?
The Full Answer :
var $ = $telerik.$;
function onClientFileUploaded(radAsyncUpload, args) {
var $row = $(args.get_row());
var inputName = radAsyncUpload.getID("TextBox");
var inputType = "text";
var inputID = inputName;
var input = createInput(inputType, inputID, inputName);
var label = createLabel(inputID);
$row.append("<br/>");
$row.append(label);
$row.append(input);
}
function createInput(inputType, inputID, inputName) {
var input = '<input type="' + inputType + '" id="' + inputID + '" name="' + inputName + '" />';
return input;
}
function createLabel(forArrt) {
var label = '<label for=' + forArrt + '>info: </label>';
return label;
}
foreach (UploadedFile UF in rada_attach.UploadedFiles)
{
if (UF.GetFieldValue("TextBox") != null)
{
OBJ.File_name = UF.GetFieldValue("TextBox");
}
else
{
OBJ.File_name = UF.GetName();
}
In my opinion documentation is well clear. Check the Description tab on page you refer on. You can access value of dynamic textboxes with code below on postback:
if (rada_attach.UploadedFiles.Count > 0) {
for (var index = 0; index < rada_attach.UploadedFiles.Count; ++index) {
var textBoxValue = rada_attach.UploadedFiles[index].GetFieldValue("TextBox");
}
}
BTW, this scenario is well-dcoumented here: Adding Information to Uploaded Files
You need to check the Request.Form values (that were in the posted form) on postback and perform a check on all the fields that were posted back.
I am guessing that you won't know the name/id of the textbox if it was created on the client-side dynamically? Note that it would be the name of the form field that the Request object in .cs would see.
Only once you have posted back can you access that value in the .cs
I have a javascript function that builds a string then sends the string to the c# codebehind to work with. Problem is, the PageMethods.Method is never being called.
pertinent code:
aspx page:
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true"
runat="server" />
<script type="text/javascript">
function makeString() {
debugger
var a = document.getElementById("ddlRptYear").value + "_";
var b = document.getElementById("ddlRptType").value + "_";
var c = document.getElementById("ddlGeography").value + "_";
var d = "";
var e = "";
var x = document.getElementById("ddlTouchPoint");
var y = document.getElementById("ddlAOR");
if (x.disabled == false) {
d = x.value + "_";
}
if (y.disabled == false) {
e = y.value;
}
var pptString = a + b + c + d + e + ".ppt";
PageMethods.GetPPTString(pptString, onSuccess, onFail);
}
codebehind:
[System.Web.Services.WebMethod]
public static void GetPPTString(string pptString)
{
if ((pptString == "") || (pptString == null))
{
throw new Exception("Error: No String Sent.");
}
else
{
throw new Exception(pptString);
}
}
I had to enable autopostback on the RadioButtonList for the SelectedIndexChanged method to be hit. It works for now, but I'll need to figure out something in the future to get past having to post back.
I got an ActionResult TabNotes which returns a View for a tab which shows notes from a database in a grid. On the tab is a button for ActionResult CreateNote, which returns a PartialView and after saving the note I redirect back to the ActionResult TabNotes with
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
However, when it goes to the action result TabNotes using this redirect it does not show the grid. The javascript gives the following error
Uncaught ReferenceError: $ is not defined (anonymous function)
Uncaught ReferenceError: ko is not defined (anonymous function)
This does not happen the first time it goes to ActionResult. Using breakpoints the following part of the ActionResult TabNotes:
[...]
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
gives the same input values in Model for the first time and the second time. Where can this error come from?
Edit: Firebug shows the following errors:
prompt aborted by user
throw Components.Exception...by user", Cr.NS_ERROR_NOT_AVAILABLE); nsPrompter.js (regel 462 <Systeem>
$ is not defined
$(document).ready(function(){$('#tblTN...tes/44?cmd=refresh" id="TNPhrase44"> 44?mod...=Phrase (regel 2)
ko is not defined
var viewModel=ko.mapping.fromJ...],"buttons":[],"PostAction":null}}); 44?mod...=Phrase (regel 12)
Below is the javascript and code
#model test.Web.Framework.Areas.Administration.Models.TabNotesModel
#using (UI.DocumentReadyScript())
{
if (Model.meta.id.HasValue)
{
UI.jQuery("#tbl" + Model.meta.modelname).flexigrid(Model.Grid);
}
}
<form method="post" action="#Url.Action("TabNotes", new { cmd = "refresh" })" id="#Model.meta.modelname">
<div class="ui-state-highlight ui-corner-all highlight" data-bind="visible: meta.message">
<span class="ui-icon ui-icon-info"></span><strong data-bind="text: meta.message">
</strong>
</div>
#using (UI.BeginBlock("Administation.TabNotes", UI.Label("Notes", "Notes").ToString(), test.Web.Framework.Core.enumIcons.pencil, false, false))
{
<table id="#("tbl" + Model.meta.modelname)">
</table>
}
</form>
<script type="text/javascript">
(function() {
var viewModel=ko.mapping.fromJS(#Html.Raw(UI.JavascriptEncode(Model)));
viewModel.getData=function() { return ko.mapping.toJSON( this ); };
viewModel.setData=function(data){
$('#tbl'+this.meta.modelname()).flexigrid( data.Grid);
ko.mapping.updateFromJS(this,data);
};
$('##Model.meta.modelname').koform({viewmodel: viewModel , validate : {errorElement:'p' } } );
$('##Model.meta.modelname').koform('applyBindings');
$('#load-partial').click(function() {
$('#partial').load('#Url.Action("CreateNote", "Entity", new {itemId = #Model.meta.id, modelEntity = "Phrase"})');
});
})();
</script>
<div id="partial"></div>
<button type="button" id="load-partial">Create Note</button>
'
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
{
if (cmd == "Save")
{
Model.meta.message = "Note saved";
test.Database.User User = UserRepository.GetUser(1);
Entity entity = NotesRepository.GetEntity("Phrase");
NotesRepository.StoreNote(Model.subject, Model.text, User, entity, itemId);
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
}
Model.meta.modelname = "CreateNote";
Model.meta.JsViewModelType = "EditNoteModel";
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId});
return PartialView("CreateNotePartial",Model);
}
'
public ActionResult TabNotes([ModelBinder(typeof(Models.JsonModelBinder))]
TabNotesModel Model, string cmd, string modelEntity, long? id)
{
if (modelEntity != null)
{
Model.meta.entity = modelEntity;
}
Entity entity = NotesRepository.GetEntity(Model.meta.entity);
if (id.HasValue)
{
Model.meta.id = id;
}
if (Model.meta.id.HasValue)
{
Model.meta.modelname = "TN" + Model.meta.entity + Model.meta.id.Value.ToString();
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId", Model.meta.id.Value);
Entity noteEntity = NotesRepository.GetEntity("Note");
var grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
grid.buttons.Clear();
//grid.buttons.Add(new Button { onpress = "CreateNote", action = Url.Action("CreateNote"), name = "CreateNote", postdata = new { meta = Model.meta }});
grid.title = "";
Model.Grid = grid;
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
'
public GridResult TabNoteData(string id, long itemId, FlexigridRequest request, string cmd)
{
GridResult returnValue = null;
var entity = NotesRepository.GetEntity(id);
Entity noteEntity = NotesRepository.GetEntity("Note");
//var Acess = UIRepository.GetEntityAccess(id);
FlexigridConfiguration grid;
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId",itemId);
grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
IQueryable q = NotesRepository.GetNotes(entity.EntityId, itemId);
var sortField = entity.EntityFields.SingleOrDefault(c => c.Name == request.sortname);
if (sortField == null)
{
request.sortname = grid.sortname;
}
IQueryable qdata = null;
if (!string.IsNullOrEmpty(request.sortname) && request.sortname != "undefined")
{
switch (request.sortorder)
{
case enumFlexigridRequestSortOrder.asc:
qdata = q.OrderBy(request.sortname + " ascending");
break;
case enumFlexigridRequestSortOrder.desc:
qdata = q.OrderBy(request.sortname + " descending");
break;
}
}
if (!string.IsNullOrEmpty(request.query) && !string.IsNullOrEmpty(request.qtype))
{
qdata = qdata.Where(request.qtype.SanitizeFieldExpression() + ".Contains(#0)", request.query);
}
if (request.q != null && request.q.Length > 0)
{
for (int i = 0; i < request.q.Length; i++)
{
var type = UIRepository.GetType(id);
var property = type.GetProperty(request.q[i]);
System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType);
string sv = request.v[i];
if (sv == null || sv == "null")
{
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", (object)null);
}
else
{
object v = tc.ConvertFromString(sv);
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", v);
}
}
}
string settingName = "Grid." + id + ".Rp";
var setting = UIRepository.GetQuery<test.Database.UserSetting>().SingleOrDefault(uc => uc.CreatedById == CurrentUser.UserId && uc.Name == settingName);
if (setting == null)
{
setting = UIRepository.Create<test.Database.UserSetting>();
setting.Name = settingName;
setting.Value = request.rp.ToString();
UIRepository.Add(setting);
}
else
{
if (request.rp.ToString() != setting.Value)
{
setting.Value = request.rp.ToString();
UIRepository.Update(setting);
}
}
int rowId = 0;
var datarows = new List<object>();
foreach (var record in qdata.Skip((request.page - 1) * request.rp).Take(request.rp).GetData())
{
var cellValues = new List<object>();
foreach (var gc in grid.colModel.OrderBy(c => c.di))
{
cellValues.Add(gc.ToString(UI, record));
}
var row = new { id = rowId, cell = cellValues.ToArray() };
datarows.Add(row);
rowId++;
}
returnValue = Grid(request.page, qdata.Count(), datarows.ToList());
return returnValue;
}
That error can only be caused be one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
You should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.
Make sure all javascript code is being run inside a code block such as:
$(document).ready(function () {
//your code here
});
This will ensure that your code is being loaded after jQuery has been initialized.
One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.
So to avoid that you can use a "bodyguard" function like the following:
( function($) {
//We can now use $ as I implemented the bodyguard!
$(document).ready(function() {
//your code...
});
} ) ( jQuery );