ReferenceError: getMessage not defined - c#

I am building a messaging area similar to facebook and I am using ajax with jquery and a asmx web service to serve the html to the client. My li click event works when the content is first loaded on page load using c#, but when ajax runs and refreshes the content from the web service the li event doesn't work anymore.
This an example of the html that is returned from the web service
<ol class="messagesrow" id="messages">
<li id="2345">
<div>Test Element</div>
</li>
</ol>
Web service markup
[WebMethod]
public string GetMessagesByObject(string id, string objectid, string userid, string timezone)
{
string output = string.Empty;
try
{
StringBuilder str = new StringBuilder();
DataSet results = results from store procedure
str.Append("<ol class=\"messagesrow\" id=\"messages\">");
for (int i = 0; i < results.Tables[0].Rows.Count; i++)
{
DataRow row = results.Tables[0].Rows[i];
DateTime date = Convert.ToDateTime(row["CreateDate"].ToString()).AddHours(Convert.ToDouble(timezone));
if (!TDG.Common.CheckStringForEmpty(row["ParentMessageID"].ToString()))
{
str.Append("<li id=\"" + row["ParentMessageID"].ToString() + "\">");
}
else
{
str.Append("<li id=\"" + row["MessageID"].ToString() + "\">");
}
str.Append("<div style=\"width:100%; cursor:pointer;\">");
str.Append("<div style=\"float:left; width:25%;\">");
if (!TDG.Common.CheckStringForEmpty(row["ImageID"].ToString()))
{
str.Append("<img src=\"/Resources/getThumbnailImage.ashx?w=48&h=48&id=" + row["ImageID"].ToString() + "\" alt=\"View Profile\" />");
}
else
{
str.Append("<img src=\"/images/noProfileImage.gif\" alt=\"View Profile\" />");
}
str.Append("</div>");
str.Append("<div style=\"float:left; width:75%; padding-top:4px;\">");
str.Append("<strong>" + row["WholeName"].ToString() + "</strong>");
str.Append("<br />");
if (row["BodyMessage"].ToString().Length < 35)
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString() + "</span>");
}
else
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString().Substring(0, 35) + "</span>");
}
str.Append("<br /><span class=\"smallGreyText\">" + String.Format("{0:g}", date) + "</span>");
str.Append("</div>");
str.Append("</div>");
str.Append("</li>");
}
str.Append("</ol>");
output = str.ToString();
}
catch (Exception ex)
{
throw ex;
}
return output;
}
Jquery markup
$(document).ready(function () {
$("ol#messages li").click(function () {
var id = $(this).attr("id");
getMessage(id);
});
});
function getMessage(id) {
var timezone = $('#<%= hdfTimezone.ClientID %>').val()
var userid = $('#<%= hdfUserID.ClientID %>').val()
$.ajax({
type: "POST",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Resources/MessageWebService.asmx/GetMessage",
data: "{'id':'" + id + "','timezone':'" + timezone + "','userid':'" + userid + "' }",
success: function (data) {
$('#<%= hdfMessageID.ClientID %>').val(id);
$('#<%= ltlMessages.ClientID %>').html(data.d);
},
error: function (data) {
showError(data.responseText);
}
});
}

Since your list items are dynamic, you should delegate the event from the ol.
$(document).ready(function () {
$("#messages").delegate("li","click",function () {
getMessage(this.id);
});
});
The error you are getting ReferenceError: getMessage not defined shouldn't happen with the given code.

Related

Print value one by one from controller in asp.net MVC, when controller is called from ajax

I have a AJAX call for controller as below,
function print(response, endpoint) {
$(".tt").append("<tr><td>" + JSON.stringify(response[0], null) + "</td><td>" + JSON.stringify(response[1], null) + "</td><td>" + JSON.stringify(response[2], null) + "</td><td>" + JSON.stringify(response[3], null) + "</td><td>" + JSON.stringify(endpoint, null) + "</td></tr>");
}
$(".submit").click(function () {
var env = $("#env").find(":selected").text();
var region = $("#region").find(":selected").text();
var country = $("#country").find(":selected").text()
var folderPath = $.trim($('#folderPath').val());
var ajaxRequest = $.ajax({
contentType: "application/json ;charset=utf-8",
type: "GET",
async: false,
url: "/Home/GetmyModel" + "?selcetion=" + env + "&region=" + region + "&country=" + country + "&folderpath=" + folderPath,
success: function (response) {
if (response != null) {
//print(response, endpoints[i]);
}
},
error: function (exception) {
},
complete: function (data) {
}
});
My controller goes like this
public void GetmyModel(string selcetion, string region, string country, string folderpath)
{
foreach (var item in System.IO.File.ReadLines(folderpath))
{
//do some work with return value as list<string>
//show list<string> in table in view using either print method of JS or by another way
}
}
Everything works fine if i send complete response back by making return type as JsonResult. However i am not understanding how can i print each item.

Bad request While Sending multipart/form-data to mvc controller using dynamically created HTML form

I have read all related question on all the portals since 2 days but i aint able to fix this issue , please look into this.
I have created a dynamic html form :
var jsprintId = "#Model.print.Id";
function DisplayIfExists(jsimageType, reqdiv) {
var d = document.getElementById(reqdiv);
$.ajax({
type: 'GET',
data: { printId: jsprintId, imageType: jsimageType },
url: '/Prints/'+jsprintId+'/Image/'+jsimageType,
success: function (response) {
if (response == "NoImage") {
d.innerHTML = "<form method='POST' action='http://localhost:5000/Prints/"+jsprintId+"/edit/UploadPrintImage' enctype='multipart/form-data' id='frmUploadIconImage'>" +
"<h1 style='text-transform:capitalize;margin-left:15px'>" + jsimageType + " Image</h1>" +
"<input type='hidden' name='printId' value='"+jsprintId+"'>"+
"<div class='row' style='margin: 1em -1em;'>" +
"<div class='col-md-10' style= 'padding: 0; overflow:hidden;'>" +
"<label type= 'text' class='form-control txtbox' id= 'lbl_svg_icon' style= 'margin-left:27px;height:34px'> Icon Image (SVG)</label>" +
"</div>" +
"<label class='btn btn-primary' for='svg_file_icon'>Browse<input type='file' name='svg_file_icon' id='svg_file_icon' style='display:none'/></label>" +
"</div>" +
"<div class='row text-center'>" +
"<input class='btn btn-primary' type='submit' value='Upload' id='btnUploadSubmit'/>" +
"</div>"
"</form>";
}
else {
d.innerHTML = "<img src='" + response + "' style='width:150px'> "
}
}
})
}
and my function for Sending this post request is :
$(function(){
$("#tabs-test").on('submit', '#frmUploadIconImage', function (form) {
form.preventDefault();
var data = new FormData(this);
if (iconImageValid) {
for (var key of data.entries()) {
console.log(key[0] + ', ' + key[1]);
}
$.ajax({
url: '#Html.Raw(Url.Action("UploadPrintImage", "Prints"))',
data: data,
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function (response) {
DisplayIfExists(jsimageType, "tabs-test");
},
error: function (error) {
console.log('your problem is ' + error.statusText);
console.log(error);
}
});
}
else {
alert("You can upload only SVG files");
$("#lbl_svg_icon").parent().addClass("has-error");
$("#lbl_svg_icon").text("SVG File");
return false;
}
});
});
the error I get is a bad request , my controller action is :
[HttpPost("Prints/{printId}/edit/UploadPrintImage")]
[Consumes("multipart/form-data")]
public async Task<ActionResult> UploadPrintImage(IFormCollection form)
{
//my code
}
it gives me the same error with all the argument type that i define i have tried the following :
public async Task<ActionResult> UploadPrintImage(FormCollection form);
public async Task<ActionResult> UploadPrintImage(HttpContext form);
public async Task<ActionResult> UploadPrintImage(HttpRequest form);
public async Task<ActionResult> UploadPrintImage(string printId, IFormfile file);
and all possible combinations but nothing works all it gives is a 400 BAD request.
following is my request screenshot:
the same code works when i have a hardcoded html form but not with dynamically created html form.
looking forward to a working solution. Thanks

Why does the data come back as undefined?

I'm not understanding why the data is coming back as undefined. It knows there is something there but the value is not being shown. Am I forgetting to do something in the main function? Thanks in advance to whom may solve my dilemma.
Here is the current output I'm getting:
Here is what I need the output to render:
Here is the code for my employee.js:
$(function() {
ajaxCall("Get", "api/employees", "")
.done(function (data) {
buildTable(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
}); // ajaxCall
});
// build initial table
function buildTable(data) {
$("#main").empty();
var bg = false;
employees = data; // copy to global var
div = $("<div id=\"employee\" data-toggle=\"modal\"data-target=\"#myModal\" class=\"row trWhite\">");
div.html("<div class=\"col-lg-12\" id=\"id0\">...Click Here to add</div>");
div.appendTo($("#main"));
$.each(data,function(emp){
var cls = "rowWhite";
bg ? cls = "rowWhite" : cls = "rowLightGray";
bg = !bg;
div = $("<div id=\"" + emp.Id + "\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"row col-lg-12" + cls + "\">");
var empId = emp.Id;
div.html(
"<div class=\"col-xs-4\" id=\"employeetitle" + empId + "\">" + emp.Title + "</div>" +
"<div class=\"col-xs-4\" id=\"employeefname" + empId + "\">" + emp.Firstname + "</div>" +
"<div class=\"col-xs-4\" id=\"emplastname" + empId + "\">" + emp.Lastname + "</div>"
);
div.appendTo($("#main"));
}); // each
} // buildTable
function ajaxCall(type, url, data) {
return $.ajax({// return the promise that '$.ajax' returns
type: type,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
});
}
Here is my Controller method code:
// GET api/<controller>
[Route("api/employees")]
public IHttpActionResult Get()
{
try
{
EmployeeViewModel emp = new EmployeeViewModel();
List<EmployeeViewModel> allEmployees = emp.GetAll();
return Ok(allEmployees);
}
catch(Exception ex)
{
return BadRequest("Retrieve failed - " + ex.Message);
}
}
The first parameter of the callback is the index, the value is in the second parameter:
$.each(data,function(index, emp){

How to add Items in jcarousel ? in C#

I would like to add Items in jcarousel using c# Webmethod + jquery Ajax
for that i made something like this :
my Html is like :
<div>
<ul id="mycarousel" class="jcarousel-skin-tango" style="float: left">
</ul>
</div>
Jquery code for jcarousel and Ajax Method is like this :
$("#mycarousel").empty();
var element =jQuery('#mycarousel');
$.ajax({
url: "Home.aspx/GetProjectData",
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: "{}",
async: false,
success: function (response) {
if (response.d != null) {
//$.each(response.d, function (i, response) {
$("#mycarousel").html('response.d');
element.jcarousel(
{
pager: true,
visible: 6
});
}
else {
}
},
error: function (xhr) {
}
});
and webmethod is like this :
[WebMethod]
public static List<string> GetProjectData()
{
// here i have 3 list in returnvalue
foreach (var item in returnvalue)
{
var classvalue = item.Soid + "|"
+ item.ProjectTitle + "|"
+ item.Role + "|"
+ item.StartDate + "|"
+ item.EndDate + "|"
+ item.Location.Country + "|"
+ item.Location.State + "|"
+ item.Location.City + "|";
string Template = "<li><img src='../Images/DefaultPhotoMale.png' class='"+ classvalue + "' width='40' height='40' alt='image'/></li>";
list.Add(Template);
}
return list;
}
but problem is , i am not able to images in jcarousel , i only see white box, i am not able to seee images inside, why ?
I'm not sure but wouldn't you need to append the elements sort of like this:
var listItem = $(response.d); //I'm guessing reponse.d is your returned li
element.append(listItem);

Passing the HTML table to JSON via Server side causing error

I've a dynamically created HTML table in the Server side code(using C#). When i pass that to client site using JASON. I couldn't able to receive that code in the client site. this is my code in the Server Side.
$.ajax({
type: "POST",
url: "ExcelUpload.asmx/UploadFile",
data: JSON.stringify({ XML: XMLDoc}),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#Status").html("<br><center><img src='ajax-loader.gif'/></center>");
},
success: function (result) {
var output = "";
var re = eval('(' + result.d + ')');
if (re.length > 0) {
for (var i in re) {
var xl = re[i];
switch (parseInt(xl.status)) {
case 1: { output = xl.message; break; }
case 2: { output = xl.message; break; }
}
}
$("#Status").html(output);
}
},
error: function (result) {
$("#Status").addClass("error");
$("#Status").html(result.d);
}
});
In that server side code I'm generating the HTML table using this code
HTML += "<table id='excelDoc'>";
HTML += "<tr><th>Date</th><th>Description</th><th>Reference</th><th>Nominal Code</th><th>Dept Code</th><th>Debit</th><th>Credit</th></tr>";
HTML += "<tr><td>" + eDoc.posting_Date.ToShortDateString() + "</td><td>" + eDoc.Description + "</td><td>" + eDoc.Ref_Number + "</td><td></td><td></td><td class='db'></td><td class='cr'></td></tr>";
HTML += "";
status = "{status : 1 , message : " + HTML + "}";
return " ["+ status+ "]";
Please Help me.
why are you doing result.d ?
Should it not be simply result ?
1 thing I notice more, in your AJAX request, your
dataType: "json"
but you are returning a simple string. Change to
dataType:"text"
and then try returning the string. It would def work

Categories