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.
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 am trying to set the value of a textfield in a rowexpander in codebehind or in js on AfterRender event listener, but I get
Cannot read property 'setValue' of undefined
Here is the textfield in the rowexpander:
<ext:TextField runat="server" Name="notedown" FieldLabel="Note Under" ID="fnotedown">
<Listeners>
<AfterRender Handler="if (form.record.data.Lid != null && form.record.data.Lid != '' )
{
setNoteUnder_js(form.record.data.id);
}" />
</Listeners>
</ext:TextField>
JS:
var setNoteUnder_js = function (fieldid){
#{DirectMethods}.setNoteUnder(fieldid,{
success: function (result) {
#{fnotedown}.setValue(result); //undefined error
}
});
}
Direct Method in Code Behind:
[DirectMethod]
public string setNoteUnder(int fieldid)
{
DAL.CDMADataContext dc = new DAL.CDMADataContext();
var field = (from f in dc.CFormFields
where f.cid == cid && f.id == fieldid
select f).FirstOrDefault();
string units = null;
if (field.Lid != null && field.Lid != "")
{
units = units + " Gender: " + field.text1 + " Unit: " + field.text2;
fnotedown.SetValue(units); //undefined error
return units;
}
return null;
}
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 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
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 );