The path is javascript path
var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath(fileName) %>
file name is error because it is javascript and not in .NET
how to put this argument in .NET Code
You'll need to use AJAX. One easy way to do it would be to use PageMethods. First, add a [WebMethod] attribute to your method:
[WebMethod]
protected static string GetListImageFilePath(string fileName)
{
This method must be static.
Then set EnablePageMethods="True" on your script manager. Then you can call your c# code from JavaScript like this:
var fileName = args.get_fileName();
PageMethods.GetListImageFilePath(fileName, function (path) {
lstImg.src = path;
});
You can't. The JavaScript runs on the client, and the asp.net code is on the server. You need to use some other way of communicating with the server eg: Ajax to a web service, a postback, etc
You simply can not do it because javascript is running at client side i.e on browser where as server code run at server. What you could do is change the your GetListImageFilePath function so that it returns the base URL for your image directory and then append the file name to create the image path.
var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath() %> + '/' + fileName;
For more information, like how server tags in Javascript are processed, I have answered a StackOverFlow thread here. Please have a look to clarify your doubt.
I think get_fileName() is server side function. So you can call it from the HTML directly.
Check these links
http://weblogs.asp.net/jalpeshpvadgama/archive/2012/01/07/asp-net-page-methods-with-parameters.aspx
http://stackoverflow.com/questions/7633557/asp-net-is-it-possible-to-call-methods-within-server-tag-using-eval
If you call the javascript function using RegisterStartupScript() or
RegisterClientScriptBlock() then these will be called in client side not in server side.
If you want to call the javascript function immediately in server side then declare an equivalent server side function.
add an ashx(http handler) in your website, then you can use lstImg.src = '/example.ashx?name=' + fileName.
public class ExampleHandler: IHttpHandler {
public void ProcessRequest (HttpContext context) {
var request = context.Request;
string fileName = (string)request.QueryString["name"];
// your logic
context.Response.Write(yourpath)
}
public bool IsReusable {
get {
return false;
}
}
}
Related
In blazor i use NavigationManager.NavigateTo(url)in order to change window location, but how can I use it to open a new tab with a specified URL without having to invoke JS on OnAfterRenderAsync()
As of 1 of June 2022 there is no way of currently doing it directly with pure Blazor, you'll need to use JSInterop. Luckily this is easy enough to do. At the top of your .razor file add
#inject IJSRuntime JSRuntime;
And then use it like so
await JSRuntime.InvokeAsync<object>("open", url, "_blank");
Note that the IJSRuntime interface itself only provides a InvokeAsync<TValue> method, the JSRuntimeExtensions class provides an extension method for IJSRuntime to directly invoke a method without a return value: InvokeVoidAsync
await JSRuntime.InvokeVoidAsync("open", url, "_blank");
Formerly, this code worked.
await _jsRuntime.InvokeVoidAsync("open", new object[2] { url, "_blank" });
At present, it now results in an uncaught exception:
> "TypeError: Converting circular structure to JSON
I found this behavior explained here (https://github.com/dotnet/aspnetcore/issues/16632):
This is because window.open returns a WindowProxy object (see
https://developer.mozilla.org/en-US/docs/Web/API/Window/open).
WindowProxy is not JSON-serializable, so can't be used as a return
value to .NET code.
To fix this, don't call window.open directly, but instead call a JS
function of your own that either returns nothing or returns something
that is JSON-serializable.
Per the above recommendation, I added the following to index.html:
<script>
window.blazorOpen = (args) => {
window.open(args);
};
</script>
And modified my C# code-behind call to pass the window arguments:
await _jsRuntime.InvokeVoidAsync("blazorOpen", new object[2] { url, "_blank" });
Effectively we now avoid the issue by discarding the WindowProxy object returned by window.open, which was formerly returned to InvokeVoidAsync and .NET was attempting to (unsuccessfully) process.
You will get TypeError: Converting circular structure to JSON when using
await _jsRuntime.InvokeVoidAsync("open", new object[2] { url, "_blank" });
or
await _jsRuntime.InvokeAsync<object>("open", url, "_blank");
This is because window.open returns a WindowProxy object (see
https://developer.mozilla.org/en-US/docs/Web/API/Window/open).
WindowProxy is not JSON-serializable, so can't be used as a return value to .NET code.
Taken from see here.
To get around this w/o using a javascript function, I use the following
await JSRuntime.InvokeVoidAsync("eval", $"let _discard_ = open(`{url}`, `_blank`)");
Just use a regular link
#UrlDescription
Per the latest change in API here is the working solution where you can add any custom object attribute to the URL as shown below:
/// <summary>
/// Show Link
/// </summary>
/// <returns></returns>
private async Task ShowLink()
{
if (this.selectedItem != null)
{
string url = $"https://example.com/sites/" + this.selectedItem.Id + "/SitePages/Reports/somepage.aspx";
//NavigationManager.NavigateTo(url, false);//opens the new page on same browser tab
string[] values = { url, "_blank" };
CancellationToken token = new CancellationToken(false);
await JSRuntime.InvokeAsync<object>("open", token, values);//opens the link in new browser tab
}
}
The best way is to:
<NavLink class="MyCssClass"
target="_blank"
href="https://www.google.com">
Google in new window
</NavLink>
I created an ASP.NET Core api controller which return a FileStreamResult object. (I can change the type of result if needed)
Here is the code of the Get function:
[HttpGet("[action]/{p_gInspectionID}/{p_nIndex}")]
public async Task<FileStreamResult> GetInspectionPictureToDownload(Guid p_gInspectionID, int p_nIndex)
{
var l_strFilePath = await GetPictureFilePathAsync(p_gInspectionID, p_nIndex);
using (var l_sReader = System.IO.File.OpenRead(l_strFilePath))
{
return (File(l_sReader, "image/jpeg"));
}
}
Now I need to consume this result in the Blazor (Webassembly) client side application.
My goal is to have a button to launch the download of the file in the browser when user clicks on it.
This should launch download functionnality of the browser.
Is it possible to achieve this in Blazor client application ?
I was trying to do the same thing, but my API was authorized, so after reading this article I end up downloading the bytes in the web assembly application and use JavaScript to download the file from the bytes.
function downloadFromByteArray(options: {
byteArray: string,
fileName: string,
contentType: string
}): void {
// Convert base64 string to numbers array.
const numArray = atob(options.byteArray).split('').map(c => c.charCodeAt(0));
// Convert numbers array to Uint8Array object.
const uint8Array = new Uint8Array(numArray);
// Wrap it by Blob object.
const blob = new Blob([uint8Array], { type: options.contentType });
// Create "object URL" that is linked to the Blob object.
const url = URL.createObjectURL(blob);
// Invoke download helper function that implemented in
// the earlier section of this article.
downloadFromUrl({ url: url, fileName: options.fileName });
// At last, release unused resources.
URL.revokeObjectURL(url);
}
here is how I solved the problem. In fact the solution was really straightforward. Thank you #Data Juggler for pointing me in the right direction.
My Blazor solution holds two project:
the server side API (Blazor server)
the client side (Blazor WebAssembly).
Here is the code for the server side:
[AllowAnonymous]
[HttpGet("[action]/{p_strPictureFilePath}")]
public IActionResult GetInspectionPicture(string p_strPictureFilePath)
{
var l_sReader = System.IO.File.OpenRead(p_strPictureFilePath);
return (File(l_sReader, "application/octet-stream", Path.GetFileName(p_strPictureFilePath)));
}
... and the code on the client side:
Added this script in client-shared.js file:
window.downloadInspectionPicture = function (p_strServerFilePath)
{
var link = document.createElement('a');
link.href = 'api/Data/GetInspectionPicture/' + this.encodeURIComponent(p_strServerFilePath);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
of course, a reference to that file is present in index.html:
<script src="client-shared.js"></script>
And finally, added a link in the razor file, and invoke script when link is clicked:
Download
#code
{
[Inject]
IJSRuntime ThisJSRuntime { get; set; }
private async Task DownloadPictureAsync()
{
await ThisJSRuntime.InvokeVoidAsync("downloadInspectionPicture", ServerFilePath);
}
}
Hope my answer is clear and can be useful to someone
I don't know if in fact your way is possible, but what I do is similar for my site https://pixeldatabase.net .
The user clicks the download button, and I show a link like this:
public async void Download()
{
// Set the ImagePath
DownloadLink = ImagePath;
}
Then on the page, I just show a Download link conditionallay:
#if (HasDownloadLink)
{
<a class="downloadlink" download="#FileName" href="#DownloadLink"
target="_blank">Download</a>
}
I have an aspx page (webforms) that is called from a jQuery Post method (which works fine), however the Response.Redirect method from the code behind does not reload the browser with the redirected URL. It does actually hit the URL, however.
I'm pretty sure this has something to do with the page being called from jQuery, but not sure why this behavior is happening.
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//lid = Validation.StripToGUID(ObjToGUID(Request.QueryString("lid")))
lid = Validation.StripToGUID(ObjToGUID(Request.Form["lid"]));
string sid = null;
if (lid.Length == 36)
{
//retrieve the link (and product data) from the database
LiveItem_Data.DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem o = new LiveItem();
o = LiveItem_Data.GetLive_ItemFromLID(lid);
if (HTTPStuff.RemoteFileExists(o.product_link))
{
Response.Redirect(o.product_link, true);
}
else
{
//generate an error
}
}
}
}
I stepped through the code and the product_link is working (manually cutting and pasting into a browser), and the remote page is being called (I'm testing the link with another site that has logging).
The browser however does not open (tried FF, IE, Opera, Chrome) the new URL.
The jQuery post:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID });
});
I verified that HTTPredirect feature is turned on in IIS Express (from Visual Studio 2012). Stumped!
I think from the jquery function, it will not redirect the page from server you will have to do this on client side itself i.e in the success part of the click function
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID }).success(function() {
//write the redirection code here
});
});
I don't think you're using post right. Post is for making a hidden service call and does not affect the browser window.
If you just want to redirect the browser window, and redir.aspx will accept either GET or POST, you can use window.location.href:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
window.location.href = "redir.aspx?lid=" + ListID;
});
If redir.aspx does not accept GET, I suggest you create a hidden form on your page (with an lid hidden input element) and post it programmatically.
I have 2 different system, lets say SystemA and SystemB.
In SystemB, there is page, say calculate.aspx, where it receive certain parameter and will perform some calculation. This page doesn't display and info, and only serves to execute the code behind.
Now i have a page in SystemA, lets say execute.aspx, that will need to call calculate.aspx in SystemB to run the desired calculation. I cannot use redirect, since that will redirect me to the calculation.aspx page on SystemB.
I had tried using HttpWebRequest but it doesn't call to the page. The code is as below:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(nUrl + '?' + fn);
myRequest.Method = "GET";
WebResponse response = myRequest.GetResponse();
Does anyone know what is the correct way of doing it? Thanks.
EDIT
Manage to get it done after changing my codes to above. Thank you all.
You can either use a web service which would be the preferred way or use AJAX to send data to the page and get result in response.
I am probably missing something obvious here, but I'm puzzled by the whole part about the data and content which I'm not used to see in a GET Request.
You should, at your choice :
convert your request to POST
remove the part concerning the data
try this
namespace SampleService // this is service
{
public class Service1 : IService1
{
public string GetMessage()
{
return "Hello World";
}
public string GetAddress()
{
return "123 New Street, New York, NY 12345";
}
}
}
protected void Page_Load(object sender, EventArgs e) // calling the service
{
using (ServiceClient<IService1> ServiceClient =
new ServiceClient<IService1>("BasicHttpBinding_IService1"))
{
this.Label1.Text = ServiceClient.Proxy.GetMessage();
//once you have done the build inteli sense
//will automatically gets the new function
this.Label2.Text = ServiceClient.Proxy.GetAddress();
}
}
refer this link
http://www.codeproject.com/Articles/412363/How-to-Use-a-WCF-Service-without-Adding-a-Service
You can create a WebMethod in your application then you call this WebMethod from any other application, you can return Json serializable or XML data from this WebMethod
Is there a way to assign/pass/copy a javascript variable to a server side variable in C#? For the sake of argument, let's say that I was able to parse some JSON for variables that I want to store and assign them on the client (ie. var = FirstName and var = 25 and var = someDateTime, etc) .
Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client. You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.
Libraries like jQuery make this kind of thing pretty simple.
There's no direct way to access variables in client-side code from your server-side code.
An easy way, without writing handlers, ajax posts, etc., to accomplish this is to simply store the java script variable in a hidden text box and retrieve it on your post. You can also write back to the hidden field and feed your script with the value, e.g.
Markup
<asp:HiddenField runat="server" Id="JavascriptValue" value="0">
Script
<script>
var myValue = <%=JavascriptValue.Value%>
</script>
Server-Side
protected void Page_Load(object sender, EventArgs e)
{
string val = JavascriptValue.Value;
}
Write the value to a control (e.g. HiddenField) via JS and read that on the postback.
You can register hidden fields from code-behind on the Page_Load
if (this.Request.Form["myHiddenField"] == null) {
ClientScript.RegisterHiddenField("myHiddenField", ""); }
populate it with a script
ClientScript.RegisterOnSubmitStatement(this.GetType(),
MethodBase.GetCurrentMethod().DeclaringType.Name + "_myHiddenField",
"var res=document.getElementById('myHiddenField');if(res!=null){res.value='some value';}");
and read it on postbacks (also Page_Load)
var myValue = (!IsPostBack)
? null
: this.Request.Form["myHiddenField"];
what I did is save the javaScript variable in a cookie and then read it from C#.
JavaScript Code:
<script>
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
</script>
C# Code:
height of browser:#Request.Cookies["height"].Value;