KnockoutJS doesn't bind fields that have been autocompleted - c#

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;

Related

How to append the values to the json filter format using c#

I have a C# method which takes the filter from URI based on the user input search in the format {"serialNumber":null,"deviceType":"Com'X 510"}.
My method also gets the serialNumber from other endpoints.
siteSNresult and partnerSNresult will fetch the external serial numbers from other endpoints.
I want the serialNumber to be appended to the filter which is fetched from the user input. Please find my code below.
public IEnumerable<EtpDevice> GetUpdatableDevices(int tenantId, [FromUri] string filter, string siteId, string partnerId)
{
var result = new List<EtpDevice>();
StringBuilder str = new StringBuilder();
var siteSNresult = "";
StringBuilder partnerSNresult = new StringBuilder();
var connectedUser = this.permissionService.GetConnectedUser();
if (siteId != "null")
{
var siteList = this.feeDataAccess.GetSitesListById(connectedUser.CurrentEnvironment, siteId);
siteSNresult = siteList.Gateways[0].SerialNumber;
}
if (partnerId != "null")
{
var partnerList = this.feeDataAccess.GetPartnerListbyId(connectedUser.CurrentEnvironment, partnerId);
foreach (var item in partnerList)
{
var partnerSN = item.Gateways[0].SerialNumber;
partnerSNresult = str.Append(partnerSN).AppendLine(";");
}
}
var finalFilter = $"{filter}" + ";" + $"{siteSNresult}" + ";" + $"{partnerSNresult}";
for (int offset = 0; result.Count() == 0 || result.Count() == _defaultLimit; offset += result.Count())
{
result = GetDevices(tenantId, offset, _defaultLimit, finalFilter).ToList();
}
return result;
}
Appended values must be in the var finalFilter. finalFilter must look something like this:
{"serialNumber":"RN-DN18184SE000078-046;AB-TEST51000000136-123","deviceType":"Com'X 510"}
How can I do this? Please help me. Thanks in advance.

Error in displaying the List of programs from database

Here i am trying to show the list of programs from database in my list.cshtml. I am not able to get the list of programs.
Suggest me if there is any wrong in code. I am facing issue in cacheUtilities as ArgumentNullException. someone help me with the code issue to get the list of programs from database.
Controller Code
[HttpGet]
[Authorize(Roles = "Affiliate")]
public ActionResult GetTrainingPrograms(int? affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
int affId = UserData.AffiliateID;
if (affiliateId != null && affiliateId.Value > 0)
{
affId = affiliateId.Value;
}
string searchStrLower = string.Empty;
string queryStr = String.Concat(affId);
// The start point in the list of Training Programs
if (start != null)
{
queryStr = String.Concat(queryStr, "-", start.Value);
}
// To find Active or Inactive at the Current Time
if (active != null)
{
queryStr = String.Concat(queryStr, "-", active);
}
// Sort the List of Data
if (sort == null)
{
sort = "trainingProgramName";
}
queryStr = String.Concat(queryStr, "-", sort);
// limit on the page to Display
if (limit != null)
{
queryStr = String.Concat(queryStr, "-", limit.Value);
}
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
searchStrLower = searchStr.ToLower();
queryStr = String.Concat(queryStr, "-", searchStrLower);
}
logger.Debug("trainingProgramListKey: " + queryStr);
TrainingProgramList reloadData = CacheUtilities.Instance.GetTrainingProgramList(affiliateId);
logger.Debug("reloadData: " + reloadData + ", affId: " + affId + ", queryStr: " + queryStr);
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + queryStr;
TrainingProgramList trainingProgramList = null;
int totalCount = 0;
// Checks the List is null or not to Display
if (trainingProgramList != null)
{
logger.Debug("Cache miss for TrainingProgram list: " + trainingProgramCacheKey);
trainingProgramList = new TrainingProgramList();
trainingProgramList.AffiliateID = affId;
totalCount = TrainingProgramRepository.Instance.GetTrainingProgramsCount(affId, searchStrLower, active);
trainingProgramList.Entries = TrainingProgramRepository.Instance.GetTrainingPrograms(affId, searchStrLower, active, sort, start, limit);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingProgramList, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationOneDay);
}
CbJsonResponse response = new CbJsonResponse();
response.Data.Add(trainingProgramList);
response.Status = "success";
response.Meta.Add("total", Convert.ToString(totalCount));
return Json(response, "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
}
}
Repository Code:
public List<TrainingProgramListEntry> GetTrainingPrograms(int affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
using (var ctx = new CrossfitPortalEntities())
{
ctx.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
// Don't need proxies when explicitly loading.
ctx.Configuration.ProxyCreationEnabled = false;
var query = ctx.TrainingPrograms.Where(m => m.AffiliateID == affiliateId);
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
query = query.Where(m => m.Name.ToLower().Contains(searchStr));
}
if (active != null)
{
}
// The property on which to sort this list.
if (sort != null)
{
switch (sort)
{
case "TrainingProgram Name":
query = query.OrderBy(m => m.Name);
break;
}
}
//The number of Training Programs to display on this page.
if (limit != null)
{
logger.Debug("TrainingProgram query limit: " + limit.Value);
}
var entries = query.Select(m => new TrainingProgramListEntry
{
Name = m.Name,
ColorCode = m.ColorCode,
// The start point in the list of Training Programs
}).Skip((start != null) ? start.Value : 0).Take((limit != null) ? limit.Value : 10).ToList();
return entries;
}
}
CacheUtilites Code:
public TrainingProgramList GetTrainingProgramList(int? affiliateID)
{
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + affiliateID;
TrainingProgramList trainingprogram = (TrainingProgramList)HttpRuntime.Cache[trainingProgramCacheKey];
if (trainingprogram != null)
{
logger.Debug("Cache hit for AffProfile Entity: " + trainingProgramCacheKey);
}
else
{
logger.Debug("Cache miss for AffProfile Entity: " + trainingProgramCacheKey);
trainingprogram = TrainingProgramRepository.Instance.GetTrainingPrograms(AffiliateID);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingprogram, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationTwoHours);
}
return trainingprogram;
}

How to get the value of the textbox which created dynamically with the Raduploader in code behind?

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

Why do I get an "$ is not defined" error?

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 );

Check and display errors in GridView

I have this codes:
private string ErrorMessage(string input)
{
{
if (!string.IsNullOrEmpty(input))
return input;
BtnImport1.Visible = false;
}
return "No value entered!";
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileNameOnServer = fileUpload.PostedFile.FileName;
string fileExt =
System.IO.Path.GetExtension(fileUpload.FileName);
if (fileUpload.PostedFile != null && fileExt == ".csv")
{
try
{
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploads"));
Label1.Text = "File name: " +
fileUpload.PostedFile.FileName + "<br>" +
fileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
BtnImport1.Visible = true;
Cancel.Visible = true;
fileUpload.Visible = false;
btnUpload.Visible = false;
}
else
{
Label1.Text = "Error - a file name must be specified/only csv files are allowed";
return;
}
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns[8]) });
myGridView.DataSource = data;
myGridView.DataBind();
}
Currently, if there are empty fields in the gridview, it will display "No value entered", but, this is only for column[1] to column [7]. If I were to upload the csv file with column[8] and column[0] containing no value, the debugger would stop as there is an error. How do I avoid this? Please help!
Change this line:
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns[8]) });
To this:
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns.Length<=8?"":columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns.Length<=8?"":columns[8]) });
UPDATE: Expanding my answer to answer second question.
Change your ErroMessage method to this:
private string ErrorMessage(string input, string dataTypeExpected="string")
{
switch (dataTypeExpected)
{
case "string": if (!string.IsNullOrEmpty(input))
return input;
break;
case "int":
int result=-1;
if (int.TryParse(input, out result))
return result.ToString();
else return "Error: value must be an integer";
}
return "No value entered!";
}
And also change the var data... part to this (pay attention how I pass columns[7] & columns[8] to the ErrorMessage method):
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns.Length<=8?"":columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7],"int"), Registration = ErrorMessage(columns.Length<=8?"":columns[8],"int") });
Explanation: I rewrote the ErrorMessage function to receive an extra optional parameter (defaulted to "string") called dataTypeExpected. You can use that parameter to indicate the data type that the input parameter should be in. If the data passed in is an empty string or a string that does not contain digits and you specify the dataTypeExpected parameter to be "int" (as I did above), the error message will say "Error: value must be an integer";
Notice that I removed the line BtnImport1.Visible = false; from the ErrorMessage method because you are executing that line once for every time the ErrorMessage is called when you only need to execute it once. So, move that line to some place else.

Categories