Im doing a Maintenance Page where people can store the description of what it will say in a Resource file, at this point in the requirement they dont even know if the text will be pure text or will have tags like <a></a>. So at this point I have to assume it will be the case.
This proyect have been made in Webforms framework 3.5 in VS2010.
For simplicity sake I'll reveal the relevant parts:
<article>
<img alt="an image" src="Images/logo.jpg"/>
<h2>Site under Maintenance</h2>
<div>
<p id="Description"></p>
</div>
</article>
<script src="Includes/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "MaintenanceSite.aspx/GetMaintenanceDescription",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Description").text(msg.d);
}
});
});
</script>
Backend:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetMaintenanceDescription()
{
string mensaje = HttpUtility.HtmlEncode(Resources.MaintenanceDescription);
return mensaje;
}
The problem is, Im receiving this on my paragraph:
<To href="">Contact Us</a>
(without the spaces as stack overflow is parsing the html correctly).
What am I missing?
There's two issues here. Firstly you need to remove the call to HtmlEncode() in the C# logic to return a plain HTML string. Secondly you need to use jQuery's html() method to display it instead of text(), as the latter will again encode the HTML.
string mensaje = Resources.MaintenanceDescription;
$("#Description").html(msg.d);
Related
I've spent 4 days trying to make an ajax call to my .aspx.cs. In the best case, I got answer in html format. I don't understand why that happened, maybe I have to add some lib from NuGet or write something in web.config?
What I tried:
[HttpPost] [HttpGet]
[WebMethod]
jQuery ajax call
change url
my first app was a sample from VS with razor pages, I thought the problem was in using razor, so I created new project - a empty web application, but I still got the same answer from server in html format.
What I want to get:
My app imitates a vending machine. A user click on buttons with coins and coins have to increase on server side. (BtnAddCoin()) Also user's coins are always showing on a panel. (ShowInsertedCoins())
ClientSide.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ClientSide.aspx.cs" Inherits="VendingMachine.ClientSide" Async="true" AsyncTimeout="60" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="stylesheet" href="StyleSheet.css" />
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function AddCoin(coin) {
alert(coin);
var val1 = coin;
$.ajax({
type: "POST",
url: "/ClientSide.aspx/BtnAddCoin",
data: '{coin: "' + coin + '" }',
dataType: "text",
success: function (data) {
alert("AddCoin" + data);
},
error: function (req, status, error) {
alert(error + status);
}
}).done(function (result) { ShowInsertedCoin(); });
}
function ShowInsertedCoin() {
var insertedCoins = document.getElementById('InsertedCoins');
alert('ShowInsertedCoin');
$.ajax({
type: "GET",
url: "/ClientSide.aspx/ShowInsertedCoins",
dataType: "text",
data: {},
success: function (data) {
alert("ShowInsertedCoin " + data);
insertedCoins.textContent = data;
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
</form>
<div>
<h1>Coffee machine</h1>
</div>
<div>
<div>
<p> Add coins: </p>
<div>
<div>
<a id ="coin1" onclick="AddCoin(1)"> 1 </a>
<a> 2 </a>
<a> 5 </a>
<a> 10 </a>
</div>
</div>
<div>
<p id="InsertedCoins" ><%=ShowInsertedCoins()%> </p>
</div>
</div>
</div>
</body>
</html>
ClientSide.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace VendingMachine
{
public partial class ClientSide : System.Web.UI.Page
{
static int coins = 10;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ShowInsertedCoins()
{
return "You inserted: " + coins.ToString();
}
[WebMethod]
public void BtnAddCoin(int coin)
{
coins = +coin;
//ShowInsertedCoins();
}
}
}
So, how I can do an ajax call to .aspx.cs with jQuery or js?
Why do I get html format when my function has to return a string?
Thanks for your attention and help.
Lots of issues here.
First issue?
You have this static value for the page class:
static int coins = 10;
You can't really control, or use or have static values in a class. The MAIN reason is such values will apply to all users of the site - not just the one user.
You can as a general rule call, use, consume static classes. In fact in vb.net, we OFTEN create a Module, and inside we have our boatload of helper routines, and routines that we freely call that library of code. While each of the routines can freely use local values, you can NOT use variables global to that module, since no instance of the class is being created, and as a result, multiple users will/would be able to set such values - and overwrite values used by other users. Worse yet, how long does the server persist such static values?
Answer: it is a total Las Vegas gamble.
this means to persist that coin count, we can choose one of MANY possible ways to persist that value.
We can have a global JavaScript variable hold the value.
We can use a control like text box to hold the value (and hide it)
We can use a hidden control (so ViewState will hold the value).
We can use ViewState directly to the hold the value (client side persisting), but is managed by server side code.
We can use session() to hold the value (server side persisting)
Over the years, we see "many" attempts to pass, share, persist data vales in a static class. It sometimes works, and often during development it "seems" to work, but the instant you deploy to a real working site, it blows up in a huge ball of flames.
So, using a static class to hold a Hodge podge of code? Sure, no problem, and that's quite much what we do in c# to obtain general "code module" of routines that we need throughout the applcation. But, be a vb.net module, or in c# a static class? Any concept of global values to that static class MUST be taken off the table and NOT used!!
Ok, so let's cook up a working example. We first have to choose a place/spot to hold and persist our coin count.
Hum, we have many choices. However, since this example code involves server side code. Then let's use session.
I mean, it would kind of defeat this whole example if we write the code 100% client-side JavaScript (which is not all that bad of a idea). However, since we attempting to learn, and use a web method?
Then let's wire this up using a web method. (as noted, we really don't need to use any server-side code here).
So, if we going to use session() to persist the value, then on first page load, we setup our coin count with a starting value of 10.
Also, WHEN you use/call/consume a web method of the page? There is NOT a instance of the page class. As a result, ANY AND ALL web methods must be static. In fact, it means really don't care if we placed the web method in the current page, is some ascx file, or wherever. Since the web page is NOT being posted back to the server, then all of the controls, values and things on that web page are STILL sitting on your desktop, and there is no copy of the web page in existence on the server side.
Next up:
data: '{coin: "' + coin + '" }',
dataType: "text",
So, you have some jason data, yet on the next line you saying we going to use text? Nope!!! If you going to pass json data the method, it going to return such json data back. Same goes if you choose xml, or whatever.
So, you can't pass json data, but then on the next line state we going to use text!!!!!
Ok, so our server side code now becomes this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// setup starting coin count
Session["CoinCount"] = (int)0;
}
}
[WebMethod(enableSession: true)]
public static void BtnAddCoin(int coin)
{
int MyCoins = (int)HttpContext.Current.Session["CoinCount"];
MyCoins += coin;
HttpContext.Current.Session["CoinCount"] = MyCoins;
Debug.Print("coins = " + MyCoins.ToString());
}
[WebMethod(enableSession: true)]
public static string ShowInsertedCoins()
{
int MyCoins = (int)HttpContext.Current.Session["CoinCount"];
return "You inserted: " + MyCoins.ToString();
}
Now, for client side, DO NOTE that when you use json format, then the return value/results are of the ".d" property of the web method. This is a asp.net thing, and it just the way it works.
So, now our client side code;
<div>
<div>
<p>Add coins: </p>
<div>
<div>
<a id="coin1" onclick="AddCoin(1)">1 </a>
<a>2 </a>
<a>5 </a>
<a>10 </a>
</div>
</div>
<div>
<p id="InsertedCoins"></p>
</div>
</div>
</div>
<script>
function AddCoin(coin) {
$.ajax({
type: "POST",
url: "/CoinCount.aspx/BtnAddCoin",
data: JSON.stringify({ coin: coin }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
// alert("AddCoin" + data);
ShowInsertedCoin();
},
error: function (req, status, error) {
alert("x" + error + status);
}
}).done(function (result) { ShowInsertedCoin(); });
}
function ShowInsertedCoin() {
var insertedCoins = $('#InsertedCoins');
$.ajax({
type: "POST",
url: "CoinCount.aspx/ShowInsertedCoins",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {},
success: function (data) {
insertedCoins.text(data.d);
}
});
}
</script>
Next up?
How did "form2" get inserted into this page?
If you create a new aspx page, (web forms), then the last gazillion pages will have by default form1, and BIG flag that you have form2 here.
Anyway, the above should work. Note that you not only are sending json data, but you as a general rule need to add the content type, and you had this missing:
contentType: "application/json; charset=utf-8",
Also, so far we only added a click event for the "1", and you have to do the same for the other 3 values you have.
As other people already commented, it's recommended to use newer technologies, other than Webforms, but if you want to continue using it or it's an project of your work or something related, here's how I normally do in Javascript:
$.ajax({
method: "POST",
url: "ClientSide.aspx/BtnAddCoin",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
obj: JSON.stringify(data)
}),
success: function (response) {
let return = JSON.stringify(response.d);
// something
},
error: function (ex) {
// something
console.log(ex.Message)
},
beforeSend: function () {
// something
},
complete: function () {
// somethin
}
});
And for the C# file, every time you want to make an webmethod, that method need to be public and static, just like that (at least I learned that every time needs to be static):
[WebMethod]
public static string BtnAddCoin(int newCoin)
{
return newCoin;
}
Try and see if that helps
I'm using web method in C# class file(i.e not a partial class of any web form) and I have html file. I just want to call web method from html file using JQuery AJAX GET and POST methods. Is it possible to do this? Is this have any sense? or i must want use asp web form?
To answer your question it's important that you first understand the prurpose of having a web service.Web services allow us to expose any piece of software over the internet and allow clients to consume it.
In .NET ASMX web services we expose software to the outside world by decorating methods with the [WebMethod] attribute.But even if we apply the [WebMethod] attribute our method will not be available over the internet unless it's inisde a:
.asmx web service file
.aspx web page
Hopefully now you understand why you can't simply define a [WebMethod] inside a standard C# class.Below is a simple example of calling an ASMX web service from a plain html page:
MyService.asmx:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string GreetUser(string name)
{
return String.Format("Hello {0}",name);
}
}
Index.html:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCallService").click(function () {
$.ajax({
type: "POST",
url: "MyService.asmx/GreetUser",
contentType: "application/json;charset=utf-8",
data: '{name:"' + $("#txtName").val() + '"}',
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" value="Call Service" id="btnCallService" />
</body>
</html>
Yes you can. Your html file can include a tag with functions that make ajax calls.
Here is a simple example from W3School's site:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
You see that the button has an 'onClick' event, which calls the loadDoc function.
And this is the function:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Here is the link to the tutorial's page:
http://www.w3schools.com/ajax/
Your Ajax Call on HTML will look very similar to this
var options = {
type: "POST",
url: '<%=ResolveUrl("~/FileLocationWhereWebMethodIsDefined") %>',
data: "{'Add Parameters if your web method needs it'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
//jQuery(".overlay").show();
//jQuery(".progress").show();
},
success: function (msg) {
},
error: function (jqXHR, textStatus, errorThrown) {
// jQuery(".overlay").hide();
// jQuery(".progress").hide();
throw Error; // "error";
}
};
jQuery.ajax(options);
I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...
Index.cshtml
#model IEnumerable<MvcApplication4.Models.tbl_product>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<title>Index</title>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
alert("button clicked");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
async: false,
Success: function (response) {
alert("Success");
window.location.reload();
},
error: function () { alert("error"); }
});
});
});
</script>
</head>
<body>
#* #using (#Html.BeginForm("Index", "Home"))
{*#
#Html.TextBox("searchString");
<input type="button" value="filter" id="Button1" />
#* }*#
<table id="showData">
#{Html.RenderPartial("SearchList");}
</table>
</body>
</html>
SearchList.cshtml(Partial View)
#foreach (var item in Model)
{
<tr>
<td>#item.ProductName</td>
<td>#item.ProductId</td>
<td>#item.ProductDesc</td>
</tr>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
ProductEntities dbentity = new ProductEntities();
public ActionResult Index()
{
return View(dbentity.tbl_product.ToList());
}
[HttpPost]
public ActionResult Index(string searchString)
{
var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
return View(query.ToList());
}
}
$.ajax({
url: '/ControllerName/ActionName',
type: "POST",
data: {criteria: 'criteria'},
contentType: "application/json",
success: function (data) {
//Replace existing table with the new view (with the table).
}
});
//write ControllerName without the key controller.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: JSON.stringify({'searchString':document.getElementById('searchString').value }),
async: false,
Success: function (response) {
alert("Success");
//append the data in between table tbody like,
$('table tbody').html(response);
//No window.location.reload(); It will cause page reload initial data will appear in grid.
},
error: function () { alert("error"); }
});
return false
Hope this helps.
Your ajax request should look like:
$.ajax({
url: '/<ControllerName>/<MethodName>',
type: "POST",
data: requestData,
contentType: "application/json;charset=utf-8",
success: function (data, textStatus, XMLHTTPRequest) {
//Success callback handling
},
error: function (XMLHTTPRequest, textStatus, errorThrown) {
//Error callback handling
},
cache: false //whether you want to cache the response or not.
});
I'm not going to give you the exact answer, but to help you to get it.
There are two steps:
First you must get sure the request is being done, and the response is being get on the browser.
To do so, you can
do it on your way: leave only the alert("Success"); and check it's being run.
better than that, open the browser's developer console (I prefer Chrome, but you can also use IE or FireFox + FireBug add-on) using F12. Set breakpoints and inspect variable values and code flow. See thit tutorial for Chrome developer tools.
set a breakpoint on the server action, and check it's executed
Second Once you're sure the firs part is working fine, use your succes function to replace the table content with the data received in the response. You can do it in several ways with jQuery. For example
$('#showData').html(response);
Again, you can execute this code and inspect the contents of response from the developer's console in your browser. This makes things eaiser when you're starting to use javascript.
(If your action generated the whole table, you could use jQuery's replaceWith which replaces the target, instead of its content. Don't use this for this case).
FINAL NOTE: please, remove this code window.location.reload();!!! This reloads the whole page with the current URL, so whatever thing you do in advance will be lost.
how can i use ajax to call a server side method i tried this code but it gives me the alert error messsage and i can't find my problem please help and thank you :
enter code here
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ImageEditor_UserControl.ascx.cs" Inherits="ImageEditor_UserControl" %>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=uploadButton.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: "ImageEditor_UserControl.ascx/helo",
data: "{}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function () { alert("success"); },
error: function () { alert("error"); }
})
return false;
});
});
</script>
<asp:Button ID="uploadButton" runat="server" Text="Upload" />
C# Code
[WebMethod]
public static string helo() {
return "Message from server.";
}
You should call *.asmx files (there are other options but this is for the beginning).
Look out for tutorials on web services & ajax consuming.
Have you checked on the line $('#<%=uploadButton.ClientID %>').click(function () { that the
<%=uploadButton.ClientID %> is actually replace by the value and not taken literally?
Do you use firefox? if yes, install the addon "FireBug". Enable firebug to check the request and the response.
Firebug will show you sometimes the error message returned from the server, as in you jquery syntax you are not loading the attributes for the method anonymous method callback for error.
error: function (req,error) { alert("error: " + req.statusText); }
This will give you a heads up on what is going wrong.
Unfortunately you cannot call a page method (server side method) that is a part of a user control. You will have to use a method in an aspx page.
I have a really simple AJAX method inside my Default.aspx.cs and it looks like this:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
And the Default.aspx looks like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="http://192.168.1.2/tizma.com/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
});
function AjaxSucceeded(result)
{
alert(result.d);
}
function AjaxFailed(result)
{
alert(result.status + " " + result.statusText);
}
</script>
</head>
<body>
<div id="Result">Click me</div>
</body>
</html>
The problem is when I click the div the ajax error function is all that is ever called with a 200 status.
What am I doing wrong?
Not sure if it's causing the problem but you have a line which reads:
data: "{}",
it should read:
data: {},
or you can omit the line altogether as it's an optional parameter to the method call. You are currently setting it to a string value when it actually expects parameters for the webmethod which might cause problems.
Also, the lines reading:
contentType: "application/json; charset=utf-8",
dataType: "json",
seem unnecessary to me because for starters, it isn't obvious that your webmethod is actually returning json. I think it's just returning a string. Try removing those three lines alltogether and see if it doesn't just start working.