I know how to do this with classic asp.
How do I do it with ASP.net?
Can I just make a code page like verifyLogin.cs
And call that page from Jquery?
Or would I have to make a page like verifyLogin.aspx with a code behind page?
There are lots of different ways to do it, depending on your requirements. Here's a very simple way to start though. Create a page called "AjaxData.aspx" with no code-behind:
<%# Page Language="C#" %>
<%
Response.ContentType = "text/plain";
string data = "some data";
Response.Write(data);
%>
Then use your AJAX call as normal:
$.get("AjaxData.aspx", function(data) {
alert(data);
});
Related
I have a website which is written in VB.NET. I do not have access to code behind and only have access aspx/ascx pages. I have some controls like this in my ascx file.
<img src="../css/icons/login.svg" />
I want to make them visible based on if user is logged in or not logged in. I remember it is possible to put the code in design files but I do not remember the syntax in VB.NET and make it visible/unvisible for these controls.
If you do not need to access that link in code behind, which would seem to be the case, you can construct the html as a ternary operator. That way you avoid binding expressions.
<%= Request.IsAuthenticated ? "Login" : "" %>
Or as an inline if statement
<% if (Request.IsAuthenticated == false) { %>
Login
<% } %>
VB Example
<% Dim IsAuth As String = IIf(Request.IsAuthenticated = False, "Login", "") %>
<%= IsAuth %>
Weird question. I need to use a JavaScript array with ID's in it, to fetch additional information from a database, using the ID's as the row ID.
I need to then use this additional information and send it to another file (aspx) using Ajax, which will then use this information to rotate images.
Unless I can use ASP Classic, and ASP.NET (C#) in the same file?
- Or can I use the more or less same ASP code to access my database?
rotate script
<%# Page Language="C#" Debug="true" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Drawing" %>
<%# Import Namespace="System.Web" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//string url = Request.QueryString["url"];
string url = #"C:\inetpub\wwwroot\testing\image.jpg";
string rotate_dir = Request.QueryString["dir"];
//create an image object from the image in that path
System.Drawing.Image img = System.Drawing.Image.FromFile(url);
//Rotate the image in memory
if (rotate_dir == "clockwise")
{
//Rotate clockwise
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
} else if (rotate_dir == "anticlockwise")
{
//Rotate anti-clockwise
img.RotateFlip(RotateFlipType.Rotate90FlipXY);
}
//Delete the file so the new image can be saved
System.IO.File.Delete(url);
//save the image to the file
img.Save(url);
//release image file
img.Dispose();
}
</script>
What I use to access my database
'Create connection and load users database
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.ACE.OLEDB.12.0"
conn.Open Server.MapPath("/nightclub_photography/data/database/jamsnaps.mdb")
Hope you understand what I'm trying to do?
As you should know you can freely use Javascript (and thus ajax) in asp-classic.
this means you can easily do the following;
set conn = Server.CreateObject("ADODB.Connection")
set rs = Server.CreateObject("ADODB.Recordset")
conn.open Server.MapPath("foobar path") + ", Microsoft.ACE.OLEDB.12.0"
%><script type="text/javascript">
rotationArray = Array(id_Array.length);
for(int i = 0; i < id_Array.Length; i++
{
<% rs.open("SELECT rotation FROM images WHERE id="+ id_Array[i])%>
rotationArray[i] = <%= rs("rotation") %>;
<%rs.close() %>
}
//send rotationArray via ajax
but in general I would suggest you use Database tools for asp.NET instead.
then you just send your JS-IDArray to the aspx file and do the processing there.
for reference you can check here
You can use C#.Net and ASP together. Its not a very nice way to do it. My understanding is you have to create the C#project first then add any asp pages. This will allow you to call your C# pages from within the asp application.
I havent personally done one of these but I have seen it done for sure so I know its technically possible.
Error:
cannot refer to an instance member of a class within a shared method
I'm working on a web application that pulls data from a MSSQL server on the backened. Calling my web method from ajax isn't the issue, it's displaying the data once it has been received.
I have the following gridview on my report page:
<asp:GridView ID="gridReport" runat="server"></asp:GridView>
The web method that is pulling the data from the DB is called DBManager.asmx, it is declared as follows (this is called via ajax each time a drop-down is changed):
<WebMethod()> _
Public Function GetSpecificReport(ByVal strFilter As String) As String()
(it is NOT the code-behind file for the report page) The data being returned from the DB is currently in a DataSet (variable name: ds).
Is there any way to assign the DataSource for that GridView to the DataSet pulled from the .asmx file, or a nice workaround that I could try? I've tried creating shared methods in the code-behind report page with no luck, as well as putting the GetSpecificReport method inside the code-behind.
Thanks for the help, let me know if I should give more info or post more code.
I would offer 3 suggestions:
First and foremost, using something like telerik grid that allows you to return JSON from your webmethod and bind directly to that json:
http://www.telerik.com/products/aspnet-ajax/grid.aspx
That said, I whipped up a small example where you can render a gridview in your webmethod and re-emit the HTML.
You can also just draw your table in HTML using RenderControl:
Here is a simplified example that re-draws the control using jquery.ajax without any updatepanel or etc. Updatepanel probably works better though!
ASPX:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="TymeJVTest._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function blag() {
var gridID = "<%= GridView1.ClientID %>";
$.ajax({
type: "POST",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
url: "Default.aspx/GetSomeData",
success: function (data) {
//not sure why this is data.d , but what the hey
var theHtml = data.d;
$("#" + gridID).html(theHtml);
},
failure: function () {
alert("Sorry,there is a error!");
}
});
}
</script>
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<a href="#"onclick="blag();" >Test</a>
</asp:Content>
CS:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int[] theObject = {1, 2, 3, 4};
GridView1.DataSource = theObject;
GridView1.DataBind();
}
[WebMethod]
public static String GetSomeData()
{
GridView gv = new GridView();
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
int[] someNewData = {10, 11, 12, 13, 14};
gv.DataSource = someNewData;
gv.DataBind();
gv.RenderControl(htmlWriter);
return stringWriter.ToString();
}
}
This will create a replacement gridview on the server, render it to html, then transmit it back.
You could also use something like AngularJS and just keep a piece of JSON that your server updates, and use this to bind to a grid in real-time with angular.
I think you can achieve what you want without too much changes using an updatepanel.
http://msdn.microsoft.com/en-gb/library/bb399001.aspx
Basically populate your grid on page load or whatever suits you then do refreshes using updatepanel.
In my code I am using a partial view (call it PV1)
<div id="div_1">
<% Html.Partial("PV1", Model); %>
</div>
and in that partial view I am using "Ajax.BeginForm" to redirect it to a particular action, hence it is doing so ...
using (Ajax.BeginForm("action1", "Forms", null, new AjaxOptions { UpdateTargetId = "div_1" }, new { id = "form1" }))
{
Response.write("I am here.");
}
public ActionResult action1(XYZ Model)
{
//
return PartialView("PV1", Model);
}
at the last line of action I am again calling the same partial 'PV1', hence it is doing this too ...
but when rendering the view it don't print or do the steps written with in partial view, it override them with and show nothing ...
Html.Partial actually returns the result of rendering the view, you want to do <%= Html.Partial() %> or <% Html.RenderPartial(); %>
Html.Partial() returns the Html and thusly must be output on the page via <%= %> and Html.RenderPartial() uses Response.Write to output onto the page and can be used with <% %>.
This is not what you would use Ajax.BeginForm for. That helper is used to create actual <form> tags that will later be submitted to the server using MVC's unobtrusive ajax (so you still need some kind of a trigger action - a button, javascript - anything that submits the form).
I'm am not very clear on what you're trying to achieve. If you want to load a partial view with ajax, I would suggest using something like jQuery's ajax load method.
I am very new to jQuery and have got a quick question.
I wish to use my server side classes in my jQuery code, something similar to this:
$(document).ready(function() {
var temp = <%# myClass.Id %>;
})
Is this possible? if so, how?
Thank you very much
This is the later question I refined my former question to:
I'm sorry, I think I didn't explain myself too well... I've got a class name User. It's a class I built in my business logic.
I've got a web page named UserProfile, inside it I've got the following property exposing the current logged in user:
public BL.User CurrUser { get { return (BL.User)Session["currUser"]; } }I want to be able to access this User class from my aspx page using Jquery. How do I do that?
The databinding syntax
<%# MyStaticClass.MyProperty %>
will only work if you call DataBind on the container (page). What you're after is most likely the following syntax:
<%= MyStaticClass.MyProperty %>
which will also give you access to you page / control members
<%= this.MyPageProperty %>
As was already mentioned you should really assign those values to java script variables and pass those variables to you JS functions.
This will only work if your javascript is embedded in your source files (e.g. the .aspx files):
<script type="text/javascript">
var id = <%# myClass.Id %>; // store as raw value
var id_string = '<%# myClass.Id %>'; // store in a string
</script>
As others have said, if the JavaScript is in your aspx page, then using server tags will work fine.
If you have your jQuery in an external script file, then you could put this in your aspx page
<script type="text/javascript">
var myClass = $('#<%= myClass.ClientID %>');
</script>
and then use the variable in your external script file
$(function() {
myClass.click( function() { ... });
});
For other options take a look at this question and answer - How to stop ASP.NET from changing ids in order to use jQuery