Object exist, object change value JS, JQuery - javascript

When my application start this JSonResult doesn`t exist and when I would like to use this (I get error "TypeError")
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
What I would like to do? I would like to have event which will tell me this object exist or this object change value.
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
How should I write this?
using System.Web.Mvc;
namespace pol
{
public class WrappedJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea></body></html>");
context.HttpContext.Response.ContentType = "text/html";
}
}
}
When I click button Image is upload to server but Result never opent important method UploadImage_Complete();
#model po.Models.Stwna
#using (Html.BeginForm("UploadImage", "StronaGlowna", FormMethod.Post,
new
{
enctype = "multipart/form-data",
id = "ImgForm",
name = "ImgForm",
target = "UploadTarget"
}))
{
<input type="file" name="imageFile" />
<input type="button" class="button" value="#Model.ZO" onclick="UploadImage()" />
}
<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute;
left: -999em; top: -999em;"></iframe>
<div id="Images">
</div>
<script type="text/javascript">
var isFirstLoad = true;
function UploadImage() {
$("#ImgForm").submit();
}
function UploadImage_Complete() {
//Check to see if this is the first load of the iFrame
if (isFirstLoad == true) {
isFirstLoad = false;
return;
}
//Reset the image form so the file won't get uploaded again
document.getElementById("ImgForm").reset();
//Grab the content of the textarea we named jsonResult . This shold be loaded into
//the hidden iFrame.
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
//If there was an error, display it to the user
if (newImg.IsValid == false) {
alert(newImg.Message);
return;
}
//Create a new image and insert it into the Images div. Just to be fancy,
//we're going to use a "FadeIn" effect from jQuery
var imgDiv = document.getElementById("Images");
var img = new Image();
img.src = newImg.ImagePath;
//Hide the image before adding to the DOM
$(img).hide();
imgDiv.appendChild(img);
//Now fade the image in
$(img).fadeIn(500, null);
// $('#Images').text(newImg.ImagePath);
}
</script>
MVC
[HttpPost]
public WrappedJsonResult UploadImage(HttpPostedFileWrapper imageFile)
{
return new WrappedJsonResult
{
Data = new
{
IsValid = true,
Message = string.Empty,
ImagePath = Url.Content(String.Format("http://a1.ec-images.myspacecdn.com/images01/29/4982945eb42646efafe2f94855ac3d21/l.jpg"))
}
};
}
I get this image when I click button twice but when I click once I don`t get any result.

I decide use Timer to make this Simple Timer

Related

two way communication between c# and JS using webview2

I'm using a webview2-control in a winforms application. I use messages to communicate between c# and Javascript
window.chrome.webview.addEventListener / window.chrome.webview.postMessage in Javascript
event .CoreWebView2.WebMessageReceived and method CoreWebView2.PostWebMessageAsString in C#
The communication works BUT only after the page in webview2 has been somehow refreshed. The first message sent by c# is always ignored/not received by JS. The messages after that are correcly received and processed.
My UI code:
public GUI()
{
InitializeComponent();
browser.Source = new Uri(System.IO.Path.GetFullPath("HTML/ui.html"));
InitializeAsync();
}
async void InitializeAsync()
{
await browser.EnsureCoreWebView2Async(null);
browser.CoreWebView2.WebMessageReceived += MessageReceived;
}
void MessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
String content = args.TryGetWebMessageAsString();
if (content.StartsWith("getData"))
{
ReadDataFromCATIA();
var serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };
string jsonRootNode = JsonConvert.SerializeObject(this.RootNode, Formatting.Indented, serializerSettings); //here I've got the message I want to post
//String input = args.TryGetWebMessageAsString();
//MessageBox.Show("string from JS: " + input);
browser.CoreWebView2.PostWebMessageAsString(jsonRootNode);
}
else //object received
{
ProductNode received = JsonConvert.DeserializeObject<ProductNode>(content);
MessageBox.Show(received.PartNumber + " received");
}
}
and my JS in ui.html
window.chrome.webview.addEventListener('message', event => {
alert(event.data);
WriteDataFromCsharp(event.data);
});
function WriteDataFromCsharp(data) {
var target = document.getElementById('target');
if (target === null) { alert('target not found') };
//alert(target.id);
//target.textContent = event.data;
rootNode = JSON.parse(data);
target.innerHTML = addTable(rootNode); //addTable create an HTML table from the deserialized object rootNode
}
function RequestData() {
//function triggered by a button on the html page
//alert('post to c#');
window.chrome.webview.postMessage('getData');
}
So far, i've tried to:
ensure the javascript is as late as possible in the page (defer, at the end of body). No changes.
inject the javascript to the page after it has been loaded using .CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(jsCode). Same behavior.
inject the javascript after once the event NavigationCompleted has fired. same behavior.
What do I miss ?
Finally found the culprit: in my HTML-page, i've used a "submit" instead of "button". With
<input type="button" value="Load data from V5" onclick="RequestData()" />
The page behavior is as expected.

how to load div in one file from another (inside iframe)

My goal is to load data from the appropriate file into div sections when I select any option.
I need to load <div> in one file from another (inside iframe). I'm stuck on how to get value and store it in variable. Everything works fine if I assign to variables (template_1, template_2, template_3) any static data but I want to load it from another files (template_one.html, template_2.html and so on).
template_1 has load() method but I know that this is wrong. Instead I want a path to appropriate file div. Same with other variables
I found a similar solution here with function load but I'm not sure if this will work and how add this to my function.
Array objects are random so please don't worry about it
jQuery(document).ready(function($) {
var template_1 = $('#section_one').load('template_one.html', '.section_one')
var template_2 = "<div><h1>template2</h1></div>"
var template_3 = "<div><h1>template3</h1></div>"
var templates_array = [
[template_1, template_1, template_1, template_1, template_1],
[template_2, template_2, template_2, template_2, template_2],
[template_3, template_3, template_3, template_3, template_3],
]
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
document.getElementById('id_template').onchange = function(event) {
let get_val = event.target.selectedOptions[0].getAttribute("value");
if (get_val) {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = templates_array[get_val - 1][i];
};
} else {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = '';
};
};
};
});
project tree
Jquery Code
$(document).ready(function(){
$(document).on('click', '#button_1', function() {
$('#div_1').load('one.html')
});
$(document).on('click', '#button_2', function() {
$('#div_2').load('two.html')
})
});
HTML Code
Button_1
<BR>
<BR>
Button_2
<BR>
<BR>
<div id="div_1"></div>
<div id="div_2"></div>
I hope this one help you.
In the iframe:
<textarea id="ta"></textarea>
<script>
$(document).ready(function(){
$(document).on('change', '#ta', function() {
parent.textAreaChanged(this.value);
});
});
</script>
In the parent:
<div id="display"></div>
<script>
function textAreaChanged(value){
$('#display').text(value);
}
</script>

How do I display an image saved within a file location in a new window by clicking a gridview link? A Terms Popup (modal) should display in between

Ok for a couple of weeks I have been stuck on a problem with one of my branches legacy applications.
I have a gridview and when I click on a link in the gridview I get a relevant image displayed within a new window. A new requirement has come in requesting that after clicking on the new window, the user should be displayed a "Terms of Use" pop up which they need to agree. After agreeing, the image should load in the new window as before.
I tried creating a popup with a modal.dialog using a bit of jquery and a div and I can get this to show. However any attempt I have made to open the image from this pop up has not worked. I think the index of the gridview gets lost when displaying the modal pop up.
The application is about 12 years old (waaaay before me). It was developed in c# and asp.net web forms.
I am new to stack. Apologies about formatting. The filestream code was in there for ages. Would there be a better way of doing this? Thank you for any help in advance.
So the user clicks on link within gridview -> A pop up displays the terms with an Agree button and ideally a cancel button too. User agrees and the popup displays image.
'''<%--button in gridview.--%>
<asp:LinkButton ID="btnOpenObject" runat="server" Text="View" OnClick="OpenObjectSelect_Click"
AlternateText="Opens Object in a new window" OnClientClick="aspnetForm.target= '_blank';" ToolTip="Opens in a new window"
CssClass="btnHyperLinkEnabled">
</asp:LinkButton>
'''<%--modal pop up.--%>
<div id="ModalMessage" title="testWindow" class="divAcceptWindow" style="display: none;">
<label style="font-weight: bold" class="boldCentral">Copying and Copyright Declaration</label>
<br />
This declaration has been issued under rule 5(3).
I declare that: blah blah…
<input type="button" id="okButton" value="I Agree" name="okButton" />
</div>
<script type="text/javascript">
//script to call popup
function showdialog() {
$("#ModalMessage").dialog({ modal: true });
$("#ModalMessage").dialog({ width: 500 });
$(".ui-dialog-titlebar").hide();
scrollTo(0, 0);
}
//script to show image from serverside
$('#okButton').click(function () {
$('#ModalMessage').dialog('close');
var dataToSend = { MethodName: 'IAgree' };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
$.ajax(options);
});
</script>
'''//c# (code behind)
'''//Gridview link button click event
protected void OpenObjectSelect_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
int miIndex = Convert.ToInt32(b.CommandArgument);
LocalSearch.DetailPosition = miIndex;
miArchiveItemId = LocalSearch.ArchiveItems[LocalSearch.DetailPosition].ArchiveItemId;
//call popup
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "showdialog()", true);
}
protected void Page_Load(object sender, System.EventArgs e)
{
//hook of jquery button click with method. This is hit after clicking I agree on pop up.
if (!Page.IsPostBack) {
if (Request.Form["MethodName"] == "IAgree") // same Method Name that we are specifying on client side
{
Agree();
return;
}
}
}
'''// Get information relating to image to pass to file stream
private void Agree()
{
ArchiveItem myArchiveItem = new ArchiveItem();
miArchiveItemId = Trunks;
if (miArchiveItemId > 0)
{
//Retrieve data from DB.
myArchiveItem = mysearchMediator.GetArchiveItemByID(miArchiveItemId);
}
DigitalObjectLink(myArchiveItem);
}
//Display the image using a file stream.
//Code works to display image without the file modal
public void DigitalObjectLink(ArchiveItem myArchiveItem)
{
LinkButton OpenObject = new LinkButton();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
OpenObject = (LinkButton)GridView1.Rows[0].FindControl("btnOpenObject");
OpenObject.OnClientClick = "aspnetForm.target ='_blank';";
}
try
{
string path = ConfigurationManager.AppSettings["ImageFilePath"] + '\\' + myArchiveItem.RelativeFolderPath +
'\\' + myArchiveItem.FileName;
//string path = "C:" + '\\' + "Temp" + '\\' + myArchiveItem.FileName;
FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] ar = new byte[(int)fs.Length];
Response.AddHeader("content-disposition", "attachment;filename=" + myArchiveItem.FileName);
Response.ContentType = "application/octectstream";
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:showdialog('" + path + "'); ", true);
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.BinaryWrite(ar);
Response.Flush();
Response.End();
}
catch
{
/*
** Hide Navigation & GridView & Show File Not Found Panel
*/
OpenObject.OnClientClick = "aspnetForm.target ='_self';";
this.NavigationControl1.Visible = false;
this.NavigationControl2.Visible = false;
this.GridView1.Visible = false;
lblFileNotFound.CssClass = "SearchResultsCount";
btnContactUs.Text = "Please contact PRONI quoting reference: " + myArchiveItem.Reference;
}
}

Add Dynamic Variable in URL Content in JQuery

I am trying to add attach my variable on my script section, since my filename is in GUID format. The filename is in hidden field:
string strDirectory = Server.MapPath(Url.Content("~/Content/AnnouncementImages/"));
string[] strFiles = Directory.GetFiles(strDirectory);
string strFileName = string.Empty;
foreach (var strFile in strFiles)
{
strFileName = Path.GetFileName(strFile);
}
<img id="myImg" src="#Url.Content("~/Content/AnnouncementImages/" + strFileName)" width="300" height="200" />
<input type="hidden" id="hiddenStringFileName" value="#strFileName"/>
In script section, I am trying to get this hidden field value:
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName');
//This is not working so far since it says cannot resolve symbol filename on below code:
modalImg.src = '#Url.Content("~/Content/AnnouncementImages/" + filename);
}
I am not sure what you are trying to do but if you want razor code plus javascript, you can put it in your view. Obviously this will no longer be unobtrusive javascript. But to do what you want, this will work. I added a button when you click it, it calls the function to show the concatenated URL.
#{
ViewBag.Title = "Test";
var strFileName = Guid.NewGuid();
}
<input type="hidden" id="hiddenStringFileName" value="#strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
<script>
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName').value;
//This is not working so far since it says cannot resolve symbol filename on below code:
var src = '#Url.Content("~/Content/AnnouncementImages/")' + filename;
alert(src);
}
</script>

Enlarge image on click of link

#foreach (var item in Model)
{
<img src='ShowShowcaseImage/#Html.Encode(item.ProductID)' id='#item.ProductID' />
<b>#Html.DisplayFor(m => item.ProductName)</b>
Enlarge
}
<div id="EnlargeContent" class="content">
<span class="button bClose"><span>X</span></span>
<div style="margin: 10px;" id="imageContent">
</div>
<p align="center"></p>
</div>
//Popup javascript
$('.enlargeImg').bind('click', function (e) {
$.post('/Home/EnlargeShowcaseImage/' + $(this).attr('id'), null, function (data) {
document.getElementById("imageContent").innerHTML += data;
});
$('#EnlargeContent').bPopup();
});
});
//
C# method
public ActionResult EnlargeShowcaseImage(string id)
{
var imageData = //linq query for retrive bytes from database;
StringBuilder builder = new StringBuilder();
if (imageData != null)
builder.Append("<img src='" + imageData.ImageBytes + "' />");
return Json(builder);
}
I want to show pop up of enlarged image on click of enlarge link. Image is stored in bytes in database. Two images are stored in database for each product - one is thumbnail and the other is enlarged. I am showing thumbnail image and I want to show enlarged image on click of enlarge link. I can't retrieve it from database.
I can't retrieve it from database
So your question is about retrieving an image from a database, right? It has strictly nothing to do with ASP.NET MVC?
Unfortunately you haven't told us whether you are using some ORM framework to access to your database or using plain ADO.NET. Let's assume that you are using plain ADO.NET:
public byte[] GetImage(string id)
{
using (var conn = new SqlConnection("YOUR CONNECTION STRING COMES HERE"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
// TODO: replace the imageData and id columns and tableName with your actual
// database table names
cmd.CommandText = "SELECT imageData FROM tableName WHERE id = #id";
cmd.Parameters.AddWithValue("#id", id);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
// there was no corresponding record found in the database
return null;
}
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead;
long fieldOffset = 0;
using (var stream = new MemoryStream())
{
while ((bytesRead = reader.GetBytes(reader.GetOrdinal("imageData"), fieldOffset, buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, (int)bytesRead);
fieldOffset += bytesRead;
}
return stream.ToArray();
}
}
}
}
and if you are using some ORM it could be as simple as:
public byte[] GetImage(string id)
{
using (var db = new SomeDataContext())
{
return db.Images.FirstOrDefault(x => x.Id == id).ImageData;
}
}
and then inside your controller action:
public ActionResult EnlargeShowcaseImage(string id)
{
var imageData = GetImage(id);
if (imageData != null)
{
// TODO: adjust the MIME Type of the images
return File(imageData, "image/png");
}
return new HttpNotFoundResult();
}
and it is inside your view that you should create an <img> tag pointing to this controller action upon button click:
$('.enlargeImg').bind('click', function (e) {
$('#imageContent').html(
$('<img/>', {
src: '/Home/EnlargeShowcaseImage/' + $(this).attr('id')
})
);
$('#EnlargeContent').bPopup();
});
But hardcoding the url to your controller action in javascript like this is very bad practice because when you deploy your application it might break. It might also break if you decide to change the pattern of your routes. You should never hardcode urls like this. I would recommend you generating this url on the server.
For example I see that you have subscribed to some .enlargeImage element. Let's suppose that this is an anchor. Here's how to properly generate it:
#Html.ActionLink("Enlarge", "EnlargeShowcaseImage", "Home", new { id = item.Id }, new { #class = "enlargeImage" })
and then adapt the click handler:
$('.enlargeImg').bind('click', function (e) {
// Cancel the default action of the anchor
e.preventDefault();
$('#imageContent').html(
$('<img/>', {
src: this.href
})
);
$('#EnlargeContent').bPopup();
});
Try jQuery,
Here is one
http://superdit.com/2011/06/11/hover-image-zoom-with-jquery/
http://demo.superdit.com/jquery/zoom_hover/

Categories