I have a gridview in the asp.net page. And each column has a button, on the click of which I am opening an Pop up using jquery.
protected void gvExpiry_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
Button tmp = new Button();
tmp = ((Button)e.Row.FindControl("btnTest"));
tmp.Attributes["onclick"] = "javascript:return MyFunc(" + gvExpiry.DataKeys[e.Row.RowIndex].Value.ToString() + "," + gvExpiry.DataKeys[e.Row.RowIndex].Value.ToString() + ")";
}
}
$("[id*=btnTest]").live("click", function () {
$("#modal_dialog").dialog({
close:function(event, ui){
$(this).dialog("close");
},
title: "Please enter tag",
buttons: {
Ok: function MyFunc(fileName, tag) {
//alert(fileName);
var etag = $("#<%= txttag.ClientID %>").val();
alert(typeof fileName);
alert(typeof Etag)
//other functionality
},
modal: true
});
return false;
});
But in my MyFunc(fileName, Etag) I'm not getting the correct values of the parameters. I am gettng object and undefined value
How can I get the correct value of my parameters
Try adding single quotes in the function call, the function thinks the text are variables, not strings.
tmp.Attributes["onclick"] = "javascript:return MyFunc('" + gvExpiry.DataKeys[e.Row.RowIndex].Value.ToString() + "','" + gvExpiry.DataKeys[e.Row.RowIndex].Value.ToString() + "')";
Related
In my GridView in C# ASP.NET 4 I insert a button to edit the row of GridView that open a new webpage on the browser in this mode
protected void btn1_Click(object sender, EventArgs e)
{
ImageButton btn1 = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int oID = Convert.ToInt32(gv.DataKeys[row.RowIndex].Values[0]);
string queryString = "newpage.aspx?oID=" + oID.ToString();
string newWin = "window.open('" + queryString + "','_blank');";
ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);
}
The newpage.aspx use Ajax and JSON for save an image on the server and close window in this mode
<script type="text/javascript">
$(function () {
$("#btnSave").click(function () {
var image = document.getElementById("cc").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
var qString = "?" + window.location.href.split("?")[1];
$.ajax({
type: 'POST',
url: 'newpage.aspx/oImage' + qString,
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Ok');
window.close();
},
failure: function (msg) {
alert(response.d);
},
error: function (msg) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(image));
}
});
});
});
</script>
Now i need refresh the Gridview after closing window
I have tried withous success these single solution, but the parent page with the GridView is not refreshed and the edited row is always available
window.opener.location.reload(true);
window.close();
Or
parent.location.reload(true);
window.close();
Or
location.href = 'gv.aspx' + qString;
window.close();
Or
window.location.replace("gv.aspx")
window.close();
Or
window.location = result.getResponseHeader('gv.aspx');
window.close();
Any suggestion?
Thanks for help.
code-behind
[WebMethod()]
public static void oImage(string imageData)
{
string folderLocation = path + "\\" + DateTime.Now.ToString("ddMMyyyy") + "\\";
bool exists = Directory.Exists(folderLocation);
if (!exists)
{
Directory.CreateDirectory(folderLocation);
}
string fileNameWitPath = folderLocation +
Guid.NewGuid() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".png";
mtsp(fileNameWitPath);
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
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.
I have an ajax calendar control used in my form for to date and from date.
The issue with it is, if I select date from previous year and click on reset button, the textbox containing date gets cleared but now when focus is set on the textbox the calendar control shows month of the year previously selected.
Is there any way we can reset calendar control as well on click of the reset button?
function Reset(divs) {
$(".ui-tooltip-content").parents('div').remove();
ClearErrorMsg();
$('#' + divs + ' input[type="text"]').val('');
$('#' + divs + ' select').val('');
$('#' + divs + ' input[type="text"]').attr({ "value": "" });
var BrwsrType = BrowserType();
if (BrwsrType == 'IE') {
$('#' + divs + ' select option').each(function () {
$("select option").removeAttr('selected');
})
};
$("select").each(function (i) {
$('select :nth-child(1)').attr('selected', 'selected')
$('select')[i].options[0].selected = true
});
var txtpagesize = $get('txtPageSize');
if (txtpagesize != null) {
txtpagesize.value = txtpagesize.attributes["defValue"].value;
$('#' + txtpagesize.id).attr({ "value": txtpagesize.attributes["defValue"].value });
}
HideDialog();
try {
Page_ClientValidate('');
}
catch (er) {
}
return false;
}
and the function which is called on reset button is as follows
function ResetForm() {
Reset('Search');
$(".dropdown").each(function () {
$('.dropdown :nth-child(1)').attr('selected', 'selected')
});
isValidDate($get('txtBeginDate'));
isValidDate($get('txtEndDate'));
HideCallOut();
$get('txtBeginDate').defaultValue = "";
$get('txtEndDate').defaultValue = "";
return false;
}
<script type="text/javascript" >
function resetcalendar()
{
$find("_Calendar").set_selectedDate(null);
$("[id*=Calendar]").val("");
$(".ajax__calendar_active").removeClass("ajax__calendar_active");
return false;
}
</script>
where _Calendar is the BehaviorID of Calendarextender and Calendar is the ID of Calendarextender
Hope this helps
Happy Coding
I have a Generic Handler (DownloadHandler.cs) which serves as both generating a pdf and downloading a pdf. When generating I use a jQuery ajax call and when downloading I use a form element which is submitted. The problem is that the form element cancels the generate request and therefore the "success" event never gets called (See image below).
Generate code (Gets called from a button):
$.ajax({
type: "POST",
url: "/DownloadHandler.ashx",
data: {
GeneratePdf: true
},
success: function (result) {
console.log(result);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
Download code (Gets called from a button):
var data = { "GeneratePdf": false }
var inputs = '';
$.each(data, function (key, value) {
inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
$('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>').appendTo('body').submit().remove();
DownloadHandler:
public void ProcessRequest(HttpContext context)
{
if (!String.IsNullOrEmpty(context.Request["GeneratePdf"]) && Convert.ToBoolean(context.Request["GeneratePdf"]))
{
Thread.Sleep(3000);
context.Response.Clear();
context.Response.Write("GENERATING");
context.Response.Flush();
}
else
{
Thread.Sleep(3000);
FileInfo pdfFile = new FileInfo(#"C:\1.pdf");
context.Response.Clear();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfFile.Name);
context.Response.AddHeader("Content-Length", pdfFile.Length.ToString());
context.Response.ContentType = "application/octet-stream";
context.Response.WriteFile(pdfFile.FullName);
context.Response.Flush();
}
}
public bool IsReusable
{
get
{
return false;
}
}
I just added a Thread.Sleep to demonstrate the generation of the pdf. Am I missing something or should I use some other method?
Maybe you can try targetting a tiny dynamic iframe on your page with your form. Something like :
var data = { "GeneratePdf": false }
var inputs = '';
$.each(data, function (key, value) {
inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
var f = $('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>');
var iframe = $('<iframe src="about:blank"/>') // should be made tiny/transparent with some css
.appendTo('body');
iframe.contents().find('html').append(f);
f.submit().remove();
I am using this code for binding asp.net gridview with right click contextmenu using jQuery but every time when I click it (use option in menu list) it reloads the page. What should I do if I want to use an UpdatePanel?
function fnView() {
var lnkView = document.getElementById('<%=lnkView.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkView.click();
}
function fnDelete() {
var lnkDelete = document.getElementById('<%=lnkDelete.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkDelete.click();
}
jQuery.fn.setEvents = function (e) {
var me1 = jQuery(this);
return this.each(function () {
var me = jQuery(this);
me.click(function (e) {
$("div").filter("[type=ContextMenu]").hide();
fnSetMenu(me.children(':first-child').text(), e.pageX, e.pageY);
});
});
};
function fnSetMenu(productID, left, top) {
if ($("#Menu" + productID).html() == null) {
var strMenuHTML = "<div type=\"ContextMenu\" id=\"Menu" + productID + "\" class=\"contextMenuClass\" mouseonmenu=\"1\"><table style='width:100%;'><tr><td onclick=fnView()>View Product</td></tr><tr><td onclick=fnDelete()>Delete Product</td></tr></table></div>";
$("body").append(strMenuHTML);
$.post("MenuHandler.ashx", {}, function (response) {
$("#Menu" + productID).html(response);
});
}
$("#Menu" + productID).css({ top: top + "px", left: left + "px" }).show();
}
$(document).ready(function () {
$("#gvProducts tr.ShowContext").setEvents();
}
);
$(document).click(function (e) {
$clicked = $(e.target);
if (!($clicked.parents().hasClass("ShowContext") || $clicked.hasClass("contextMenuClass") || $clicked.parents().hasClass("contextMenuClass"))) {
$("div").filter("[type=ContextMenu]").hide();
}
});
use jQuery's live function to bind an event inside updatepanel
or
go through this link
http://stackoverflow.com/questions/256195/jquery-document-ready-and-updatepanels