I am adding some html/css in div.InnerHtml by applying foreach loop reading each directory contents to post images, and i want to call function showfile(dynamic parameter) into it.
how should i do this?
the showfiles(dynamic parameter) function is working fine, but i want to make it work after user clicks the controls generated in div, which is not working, please have a look on my code and give me suggestion.
public void Showimages( string fname)
{
string name = Path.GetFileName(fname); //select only name.ext
str2 = "<div style='max-width:250px; max-height:170px;'>"
+ "<a href ='" + filepath2 + "/" + name + "' >"
+ "<img class='img-responsive' src='" + filepath2 + "/" + name + "'>"+name+"</a></div>"; //post image + name in loop
imgcontainer.InnerHtml += str2;
}
public void Generatecontrol(string dp)
{
//linkdiv.InnerHtml += "<asp:LinkButton runat='server' class='linkb' OnClick='Showfiles(" + dp.ToString()+ ")' >" + dp.ToString() + "</asp:LinkButton><br />";
linkdiv.InnerHtml += "<span class='col-lg-4'><asp:LinkButton runat='server' class='col-lg-4 linkb' OnClick='Showfiles' CommandArgument=" + dp.ToString()+ " ><img src='/pimages/folder.jpg' height='75' width='75' border='0'/><br />" + dp.ToString() + "<br /></asp:LinkButton></span>";
}
See you are passing the value as CommandArgument, so you have to take the same from CommandArgument. Change the signature of Showimages like the following:
public void Showimages(object sender, CommandEventArgs e)
{
string name = Path.GetFileName(e.CommandArgument.ToString());
// your code here
}
Pritesh,
If your main concern is only displaying images dynamically, then you can use jquery, here below I prepared a small snippet, please look at once,
Backend code:
public List<string> GetImages()
{
string fileName = "";
string[] files = System.IO.Directory.GetFiles("");
List<string> listImages = new List<string>();
foreach (string file in files)
{
fileName = System.IO.Path.GetFileName(file);
listImages.Add(fileName);
}
return listImages;
}
HTML:
<div class="row" style="margin-top:20px;">
<div id="imgPreview"></div>
</div>
<button id="btnShowImage" onclick="ShowImages()">Show Image</button>
Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function ShowImages() {
$("#imgPreview").html("");
$.ajax({
type: 'post',
url: '/xyz/GetImages',
data: formData,
success: function (response) {
if (response != null) {
var imageList =DisplayImages(response);
$("#imgPreview").append(imageList);
}
},
processData: false,
contentType: false,
error: function () {
alert("Whoops something went wrong!");
}
});
}
)};
function DisplayImages(data) {
var imageDiv ="";
if (data != null) {
$.each(data, function (index, value) {
//This is for dynamically generating image div. You can manipulate this section as per you need.
imageDiv = "<div style='max-width:250px; max-height:170px;'>";
imageDiv += "<a href ='~/your static path/" + value + "' >";
imageDiv += "<img class='img-responsive' src='='~/your static path/" + value + "'>" + value + "</a></div>";
});
}
return imageDiv;
}
</script>
Let me know if it helped.
Related
Fiddled with every imaginable combination of webapi controller and jquery ajax script which, when debugging, does make a get call to the controller, but it won't parse the data (in debug, the data is there!). PostMan and typing URL into browser works perfectly, so I believe there is (yet another) trick to get jquery.ajax to work.
the WebAPI controller method (which works):
namespace SearchWebsite.Controllers
{
public class MoreInfoController : ApiController
{
private string DBConnStr;
public MoreInfoController()
{
DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem_Data.DBConnStr = DBConnStr;
}
[Route("api/getmoreinfo/{lid}")]
[HttpGet]
public async Task<IHttpActionResult> GetMoreInfo(string lid)
{
var retval = new AppCore.MoreInfo();
if (lid.Length == 36)
{
if (IsGUID(lid))
{
retval = await LiveItem_Data.GetMoreInfoAsync(lid);
}
}
return Ok(retval);
}
}
}
And I get the expected results when I call it via postman or the browser, like so:
https://localhost:44371/api/getmoreinfo/2A116FF3-E6C8-4EE3-88E5-99001DCCE36A
The jquery ajax method:
$(".popInfo").bind("click", function (e) {
var ListID = $(this).parent().parent().find('[id*=hidlid]').val();
$.ajax({
type: "get",
url: "../../api/GetMoreInfo/" + ListID,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
try {
var mi = jQuery.parseJSON(data);
var img = "";
if (mi.IMGLNK != "") { img = "<img src='" + mi.IMGLNK + "' class='img-responsive' />"; }
var title = "<a href='redir?lid=" + ListID + "' target='_blank' >" + mi.NAME + "</a>";
var btnV = "<a href='redir?lid=" + ListID + "' target='_blank' class='btn btn-success' ><span class='glyphicon glyphicon-shopping-cart'></span> Visit Website</a>";
var btnR = '</span> Report Problem';
var details = "<p><p>SKU: " + mi.SKU + "</p><p>MPN: " + mi.MPN + "</p><p>UPC: " + mi.UPC + "</p><p>Ship Weight: " + mi.WT + " lbs</p><p>Last Updated: " + formatJSONDate(mi.MD) + "</p></p>"
$('#moreinfo').find('.modal-title').html(title);
$('#moreinfo').find('.modal-body').html(img + '<p class="descr">' + mi.DESC + '</p>' + details);
$('#moreinfo').find('#btnVisit').html(btnV);
$('#moreinfo').find('#btnReport').html(btnR);
$('#moreinfo').off().modal('show');
} catch (e) {
alert("ERROR:" + e + " data: " + data + " mi: " + mi);
}
},
error: function (err) {
alert("error: " + err);
}
});
});
the try catch and alerts are for troubleshooting, however even though the data is in the data variable while stepping through and debugging, the "data" becomes undefined immediately after using parseJSON(), and, naturally, the variable "mi" is undefined as well and the error I trapped is "SyntaxError: Unexpected token u in JSON at position 0 data: [object Object]".
I'm at a loss as how to remedy this issue. (note: I am in the process of converting old ASMX services into MVC5 WebAPI 2.1 services, so DotNetCore answers won't work as it's a completely different beast, as is MVC4 and below)
I want to return javascript function from asmx as string like following..
All html tags return but checkNewMsg variant 'script tag' doesnt return!
What happens really ?
Please advice
<script type="text/javascript">
function getWindow(FromUserID, UserID, PerID, UserName) {
$.ajax({
type: "POST",
url: "TestMessageService.asmx/OpenWindow",
data: "{'FromUserID': '" + FromUserID + "', 'ClickedUserID': '" + UserID + "', 'ClickedPerID': '" + PerID + "', 'ClickedUserName': '" + UserName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var msgs = response.d;
$('#div_Panel').append(msgs).fadeIn("slow");
var elements = $('.panelContent');
for (var i = 0; i < elements.length; i++) {
elements[i].scrollTop = elements[i].scrollHeight;
}
},
failure: function (msg) {
$('#div_Panel').text(msg);
}
});
}
</script>
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string OpenWindow(string FromUserID, string ClickedUserID, string ClickedPerID, string ClickedUserName)
{
string checkNewMsg = "<script type=\"text/javascript\">window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }</script>";
StringBuilder sb = new StringBuilder();
sb.Append(checkNewMsg + "<div class=\"ch_Box\">");
sb.Append("<div class=\"ch_Header\">");
sb.Append("<div style=\"float:left;margin-top: 9px;margin-left: 8px;\"><img src=\"Images/Status.png\"></div>");
sb.Append("<div id=\"roomUsers\" class=\"ch_HeaderItem\">" + ClickedUserName + "</div>");
sb.Append("<div onclick=\"closePanel(this)\" style=\"width: 23px; height: 27px; cursor: pointer; position: absolute; margin-left: 232px;\"><img style=\"height: 20px; margin-top: 4px;\" src=\"Images/close.png\"></div>");
sb.Append("<div id=\"cont_" + ClickedUserID + "\" class=\"panelContent\">" + FillMessages(roomID, FromUserID.ToInt()) + "</div>");
sb.Append("<div class=\"ch_Text\">");
sb.Append("<input id=\"msg_" + FromUserID + "_" + ClickedUserID + "_" + ClickedPerID + "_" + roomID + "\" type=\"text\" class=\"inp\" onkeypress=\"PushText(this)\" autocomplete=\"off\" /></div>");
sb.Append("</div></div>");
return sb.ToString();
}
I don't know why doesn't return script tag an asmx but when i remove the tag and then in the js side while i add script' tag before return value the problem is solved.
Just like this;
In asmx side;
string checkNewMsg = "window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }#func#";
In Js Side;
success: function (response) {
var msgs = response.d;
var arrCont = msgs.split('#func#');
var MsgCont = "<script type=\"text/javascript\">" + arrCont[0] + "<\/script>";
I trying to add HTML or image button which can call code behind method, from a static method(Web method), I am calling web method through AJAX. My code is:
AJAX Method
function dispData()
{
var text_data = document.getElementById("TextBox1").value;
var text_count = text_data.length;
if (text_count >= 4)
{
alert("Text box val = " + text_data + " :Count = " + text_count);
$.ajax({
type: "POST",
url: "WebForm2.aspx/ajaxData",
data: JSON.stringify({ data: text_data }),
contentType: 'application/json; charset=utf-8',
dataType: "JSON",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
//alert("We returned: " + result.d);
$('#disp_ajax_data').html(result.d);<-- displaying result in div
}
})
return false;//end of ajax
}//end of if text_count.
}//end of dispData.
[WebMethod(TransactionOption = TransactionOption.Supported)]
public static string ajaxData(string data)
{
for (int loopCount = 0; loopCount < myCount; loopCount++)
{
string ele = oCompInfoSet[loopCount].Name + "<a href='codeBehindMethod()'>Add</a>" + "<br>";
returnVal += ele;
}//end for loop.
}
I am displaying the names properly but not able to get the buttons. Can anyone please help
EDIT:
From deostroll's help, my changed code, Oh... silly me.... I missed 'Static' keyword. I am trying to pass value now
for (int loopCount = 0; loopCount < oCompInfoSet.ComponentCount; loopCount++)
{
//Debug.WriteLine("In for loop");
string ele_name = oCompInfoSet[loopCount].Component.Name;
string ele = ele_name + "<a href='#' OnClick='add_ele("+ele_name+")'>Add</a> <br>";
returnVal += ele;
}//end for loop.
[WebMethod(TransactionOption = TransactionOption.Supported)]
public static void addToStream()
{
Debug.WriteLine("Add to stream here");
}//end of addToStream
JS METHOD:
function add_ele(name)
{
alert("add ele called, "+name);
//PageMethods.addToStream();
}//end of add_ele.
I am not getting alert also now, getting "Unidentified Error"....
Try looking at this: http://visualstudiomagazine.com/articles/2007/08/28/creating-and-consuming-aspnet-ajax-page-methods.aspx
The article above utilizes a concept called Page Methods. You have to enable it on the ScriptManager. Here is a simple example that is kind of in line with what you are doing:
Aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.PageMethods.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page Methods</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>
<div>
<input type="button" onclick="GenerateLinks(5)" value="Add Links" />
<div id="links"></div>
<ul id="result">
</ul>
</div>
</form>
<script>
/*
*
* to generate guid
*
*/
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function GetTime() {
var g = guid();
log('sent request for ' + g);
PageMethods.GetTime(g, GetTimeSuccess);
}
function GetTimeSuccess(result) {
log('result:' + result);
}
function GenerateLinks(n) {
log('Generating links');
PageMethods.GenerateLinks(n, function (result) {
document.getElementById('links').innerHTML = result;
log('added links');
});
}
function log(msg) {
var dt = new Date();
var format = function(number){
return number < 10 ? '0' + number : number
};
var h = format(dt.getHours());
var m = format(dt.getMinutes());
var s = format(dt.getMinutes());
var ul = document.getElementById('result');
var li = document.createElement('li');
li.innerHTML = h + ':' + m + ':' + s + ' - ' + msg;
ul.appendChild(li);
}
</script>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Web.Services;
namespace WebApp.PageMethods
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GenerateLinks(int number)
{
List<string> a = new List<string>();
for (int i = 0; i < number; i++)
{
a.Add("Get Time " + (i + 1) + "");
}
return string.Join("<br/>", a);
}
[WebMethod]
public static string GetTime(string guid)
{
return guid + " / " + DateTime.Now.ToLongTimeString();
}
}
}
I have a calender control and on selecting a respective date, I need to display Today's Due and Over due as two section in an accordion. I have written the div for accordion in code behind and set style.css to give the look of Accordion. The data from code behind is converted into json and displayed. The code behind is as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CalenderBinderAccordian()
{
try
{
//Code to fetch productGroup is not shown
foreach (var p in productGroup)
{
var todoCount = 1;
string todoString = "";
int uniqueID = Guid.NewGuid().GetHashCode();
todoString = "<div class='accordion vertical'><section id='" + uniqueID + "' style='overflow-y: scroll;'> <h2><b>Due Today</b></h2>";
foreach (var t in p.todo)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='www.google.com' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
}
todoString += "</section>";
var overDue = temps.Select(x => new { x.DueDate }).Distinct().ToList();
int overDueCount = 0;
uniqueID = Guid.NewGuid().GetHashCode();
todoString += "<section id='" + uniqueID + "'> <h2><b>Over Due</b></h2>";
int todoCount1 = 1;
for (int i = 0; i < overDue.Count(); i++)
{
if ((Convert.ToDateTime(overDue[i].DueDate) - Convert.ToDateTime(p.dates)).Days < 0)
{
overDueCount++;
var overDueList = temps.FindAll(x => x.DueDate.Equals(overDue[i].DueDate)).ToList();
foreach (var t in overDueList)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
//Error occurs when the href is given as aspx
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount1.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='PaymentDetails.aspx' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
todoCount1++;
}
}
}
todoString = todoString + "</section></div>\",\"count\":\"" + todoCount + "\"},";
jsonString = jsonString + String.Format("{{\"{0}\" : \"{1}\",\"{2}\" : \"{3}", "dates", p.dates, "todo", todoString);
if (overDueCount.Equals(0))
{
jsonString = jsonString.Replace("</section><section id='" + uniqueID + "'> <h2><b>Over Due</b></h2></section>", "</section>");
}
}
jsonString = jsonString.TrimEnd(',');
jsonString = '[' + jsonString + ']';
string data= jsonString; JavaScriptSerializer().Serialize(productGroup);
return data;
}
catch (Exception ex)
{
throw;
}
}
//How to data is converted to Jsonvar tododate = [];
$(window).bind('loaded', function () {
$.ajax({
type: "POST",
url: "ChartBinder.asmx/CalenderBinderAccordian",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
tododate = JSON.parse(msg.d);
},
error: function (msg) {
alert("error");
}
});
});
Kindly note when the href is given as www.google.com the functionality works well but when it is given as PaymentGateway.aspx It does not display date in accordion format rather shows error alert.
Using Firebug, Noticed the following Error:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
Solution: Tried changing the configuration :
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
Nothing happaned when i try do this in release mode but in debug mode all work fine - why???
When i adding button and outputing data by clicking this buton.My inner links in my list rows work fine also ( http://clip2net.com/s/2AG04 ).And only on $(document).ready(function () { event this doesn't want to work...
On client i have:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index", "Product")',
cache: false,
type: 'GET',
dataType: 'json',
proccessData: false,
contentType: 'application/json; charset=utf-8'
});
On server i have this:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//Отправляем на клиент данные
_senderHub.SendMessage();
return null;
}
return View();
}
Also on server:(SignalR)
readonly ManagerDB _managerDB = new ManagerDB();
public void SendMessage()
{
IEnumerable<ProductModels> list = _managerDB.GetListOfProduct1();
var listToClient = new List<ProductModels>();
foreach (var prod in list)
{
listToClient.Add(new ProductModels
{
Id = prod.Id,
Name = prod.Name,
LockType = prod.LockType,
LockTime = prod.LockTime,
LockUser = prod.LockUser,
TimeStampF = prod.TimeStampF
});
}
var anonimProduct = listToClient;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SenderHub>();
context.Clients.AddListRows(anonimProduct);
}
On client(SignalR) trying catch this data:
$(function () {
var senderHub = $.connection.senderHub;
senderHub.AddListRows = function (data) {
var dataFromServer = data;
var listOfData = "";
for (var i = 0; i < dataFromServer.length; i++) {
$("#ListOfProductsTableBody").html(null);
var userId = '';
if (dataFromServer[i].LockUser != null) {
userId = dataFromServer[i].LockUser;
}
listOfData += ("<tr><td>" + dataFromServer[i].Id + "</td><td>" + dataFromServer[i].Name + "</td><td>" + userId + "</td><td>" + dataFromServer[i].LockType + "</td>" + "<td id=\"ModifyBlock\"><a id=\"Detail\" href=\"#\" alt=" + dataFromServer[i].Id + " >Детально</a>|<a id=\"Delete\" href=\"#\" alt=" + dataFromServer[i].Id + " >Удалить</a>|<a id=\"Edit\" href=\"#\" class=\"" + dataFromServer[i].LockTime + "\" alt=" + dataFromServer[i].Id + " >Редактировать</a></td></td></tr>");
}
$("#ListOfProductsTableBody").append(listOfData);
};
$.connection.hub.start();
});
emphasized text
See David Fowler's response to my question. Looks like you have the same issue.
Server to client messages not going through with SignalR in ASP.NET MVC 4