Not sure what I'm doing wrong but I can't get my JQuery AJAX call to pass the variable properly. It recieves it just fine. I'm probably overlooking something minor. Thanks.
(Also, is there any way to pass data this way without using a [WebMethod] or via the URL?)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#button').click(function(){
var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "', '" + $('#t2').val() + "' : '" + $('#p2').val() + "'}";
$.ajax({
type: "POST",
url: 'Default.aspx/test',
contentType: 'application/json; charset=utf-8',
data: "thisisatest",//json_obj,
dataType: 'json',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
});
});
</script>
</head>
<body>
<div>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
</div>
</body>
</html>
Code Behind
[WebMethod]
public string test(string json)
{
return json;
}
Here's a full example I wrote for you to illustrate the concept:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
public class MyModel
{
public string T1 { get; set; }
public string P1 { get; set; }
public string T2 { get; set; }
public string P2 { get; set; }
}
[WebMethod]
public static string Test(MyModel obj)
{
return "Hello from test";
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
<script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$('#button').click(function () {
var data = JSON.stringify({
obj: {
t1: $('#t1').val(),
p1: $('#p1').val(),
t2: $('#t2').val(),
p2: $('#p2').val()
}
});
$.ajax({
url: 'default.aspx/test',
type: 'POST',
contentType: 'application/json',
data: data,
success: function(result) {
$('#result').html(result.d);
}
});
return false;
});
</script>
</body>
</html>
I have mixed here the code behind and the markup in the same Default.aspx file but obviously you could have them separate if you prefer.
WebMethods must be static!
http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
[WebMethod]
public static string test(string json)
{
return json;
}
and your JSON input should be :
var jsonInput = { 'json': 'XXXXXXX'};
where 'json' is equal to the name of the webmethod parameter
and in the Ajax function
data:JSON.stringify(jsonInput)
You can change the method to GET and append the value to the URL like so...
$.ajax({
type: "GET",
url: 'Default.aspx/test?json=' + 'thisisatest',
contentType: 'application/json; charset=utf-8',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
Then in your code behind....
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json; charset=utf-8";
Response.Write(Request["json"]);
}
If You're going to go this route though, I'd recommend not using Code Behinds as they have to process the entire ASP.NET Web Forms Page Life Cycle. You're better of using ASP.NET Handlers (ashx).
Good luck!
Related
I have tried looking at answers to similar questions and none of them work for my code. I have tried a lot of different things, all it should do is post the fullname and then display it back in the view.
The view code:
<script type="text/javascript">
$(document).ready(function () {<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo2').click(function () {
var fullName = $('#fullName').val();
var payload = {fn : fullName};
$.ajax({
type: 'POST',
url: '/demo/demo2/',
contentType: 'application/json',
data: JSON.stringify(payLoad),
success: function (result) {
$('#result2').html(result);
}
});
});
</script>
<fieldset>
<legend>Demo 2</legend>
Full Name <input type="text" id="fullName" />
<input type="button" value="Demo 2" id="buttonDemo2" />
<br />
<span id="result2"></span>
</fieldset>
The controller code:
[HttpPost]
public IActionResult Demo2(string fullName)
{
return new JsonResult("Hello " + fullName);
}
First, when you pass string by ajax to action,you should ensure the received parameter name is the same as the incoming parameter name.
So, you should change var payload = {fn : fullName}; to var payload = {fullName: fullName};, or change public IActionResult Demo2(string fullName) to public IActionResult Demo2(string fn).
Then, because you passed only a string not an object parameter , so you don't need to use JSON.stringify, and remove contentType: 'application/json' .
Here is the detailed code:
<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo2').click(function () {
var fullName = $('#fullName').val();
var payload = { fullName: fullName }; // change name
$.ajax({
type: 'POST',
url: '/demo/demo2/',
// contentType: 'application/json', // remove this line
data: payload, //remove JSON.stringify
success: function (result) {
$('#result2').html(result);
}
});
});
});
</script>
<fieldset>
<legend>Demo 2</legend>
Full Name <input type="text" id="fullName" />
<input type="button" value="Demo 2" id="buttonDemo2" />
<br />
<span id="result2"></span>
</fieldset>
Controller:
[HttpPost]
public IActionResult Demo2(string fullName)
{
return new JsonResult("Hello " + fullName);
}
Here is the test result:
I am writing simple web service to save the data in cache and then retrieve it. When I press the save button, AJAX code runs on server and browser console shows me this error. My C# web service code is:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class stash : System.Web.Services.WebService
{
[WebMethod]
public bool save_value(string new_value)
{
//Session["newValue"] = new_value;
HttpRuntime.Cache["newValue"] = new_value;
if (HttpRuntime.Cache["newValue"] != null)
{
return true;
}
else
{
return false;
}
}
[WebMethod]
public string get_value()
{
object a = HttpRuntime.Cache["newValue"];
return a.ToString();
}
}
And html page code is ..
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
main page
</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#savebtn").click(function () {
var val = $("#txtsave").val();
$.ajax({
url: "stash.asmx/save_value",
method: 'POST',
contentType: 'application/json;charset-utf',
data: JSON.stringify({ new_value: val }),
dataType: 'bool',
//cache: true,
success: function (data) {
if (data == true) {
alert("value has been saved");
}
else {
alert("value did not saved");
}
},
});
});
$("#getbtn").click(function () {
$.ajax({
url: "stash.asmx/get_value",
method: 'GET',
datatype: 'json',
cache: true,
success: function (data) {
$("#txtget").val(data);
},
});
});
});
</script>
</head>
<body>
Type the value u want to save : <input type="text" id="txtsave" />
<input type="button" id="savebtn" value="save it" /><br /><br /><br />
get the value u just saved by pressing this button <input type="button" id="getbtn" value="get" />
<input type="text" id="txtget" />
</body>
</html>
I am new to MonoDevelop, C#, and Linux. To learn how things work, I'm trying to make a simple web page to input the height and width of a rectangle, then use a submit button to calculate and display the area.
I have two problems. First, I can't get the submit button to actually do anything. Second, I'm having trouble getting the value of the textboxes in the C# code. Once I get it, I think I can handle the values okay to calculate the area and spit it back out. The Request.Form commands were my point of problem I believe.
Here's what I have so far:
<body>
<div>
Height <input type="text" name="inHeight" value=1 /><br />
Width <input type="text" name="inWidth" value=1 /><br />
<br />
<input type="button" name="btnCalculateArea" value="Calculate Area" onclick="CalculateArea()" /><br />
<br />
<%= Html.Encode(ViewData["Message"]) %>
</div>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace rectangle_area.Controllers
{
public class HomeController : Controller
{
public string strHeight;
public string strWidth;
public int intHeight;
public int intWidth;
public double dblArea;
public ActionResult Index ()
{
return View ();
}
public ViewResult CalculateArea ()
{
strHeight = Request.Form ["inHeight"];
strWidth = Request.Form ["inWidth"];
if (strHeight != null && strWidth != null) {
intHeight = Convert.ToInt16 (strHeight);
intWidth = Convert.ToInt16 (strWidth);
dblArea = intHeight * intWidth;
ViewData ["Message"] = "The area of this rectangle is " + dblArea + " square units.";
} else {
ViewData ["Message"] = "Please enter values for the Height and Width.";
}
return View ();
}
}
}
You have to bind there a function that makes an ajax call to your controller.
Thanks for the direction, Christos! With the help of a friend and more research, I got it working. Here's what I ended up with:
<head runat="server">
<title>Calculate the area of a rectangle</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/Home/CalculateArea';
$('#calcBtn').click(function(){
$.ajax({
type: "GET",
url: serviceURL,
data: { inHeight: $("#inHeight").val(), inWidth: $("#inWidth").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
<body>
<div>
Height <input type="text" id="inHeight" value=2 /><br />
Width <input type="text" id="inWidth" value=3 /><br />
<br />
<input id="calcBtn" type="submit" value="Calculate Area" /><br />
<br />
</div>
</body>
[HttpGet]
public ActionResult CalculateArea ()
{
strHeight = Request.Params ["inHeight"];
strWidth = Request.Params ["inWidth"];
if (strHeight != null && strWidth != null) {
intHeight = Convert.ToInt16 (strHeight);
intWidth = Convert.ToInt16 (strWidth);
dblArea = intHeight * intWidth;
ViewData ["Message"] = "The area of this rectangle is " + dblArea + " square units.";
} else {
ViewData ["Message"] = "Please enter values between 0 and 999.";
}
return Json(ViewData["Message"], JsonRequestBehavior.AllowGet);
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1
-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Login Page</title>
<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="wholeContent">
<div id="login">
<table border="2">
<tr>
<td>
User Id
</td>
<td>
<input type="text" id="txtId" name="txtId" />
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="text" id="txtPwd" name="idPwd" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btnSubmit" value="Login" />
</td>
</tr>
</table>
</div>
<div id="success">
</div>
<div id="error">
</div>
</div>
<script type="text/javascript">
$(document).ready(function()
{
$("#btnSubmit").click(function()
{
var uid = $("#txtId").val();
var pwd = $("#txtPwd").val();
var data=JSON.stringify({uid:uid,pwd:pwd});
$.ajax({
type: "POST",
url: "Default.aspx/ValidationWebMethod",
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
// data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
success: function (data)
{
alert(" Successful Login "+data.d);
// location.reload();
},
error: function(resp,textStatus,errorThrown)
{
alert("error : " + errorThrown + " || Check your Id and Password || "+ resp.d);
}
});
});
});
</script>
</form>
</body>
</html>
This is my code-behind (part of the code)
[System.Web.Services.WebMethod]
public static void ValidationWebMethod(string uid, string pwd)
{
string text = uid + " : " + pwd;
System.IO.File.WriteAllText(#"D:\TrackLog.txt", text);
string[] flags = new string[1];
// bool valid = true;
if (uid.Equals("arijit") && pwd.Equals("admin"))
{
flags[0] = "true";
// return flags;
}
else
{
flags[0]="false";
// return flags;
}
}
Now when I am clicking the button (btnSubmit) its giving syntax error:Invalid Character (the errorThrown variable here in the alert box)..Please can you tell me why is it happening?
The problem is here
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
As you changed the data in json format with JSON.stringify
var strdata=JSON.stringify({uid:uid,pwd:pwd});
So you no need to pass data to ajax method like you do above.
Try this
data: strdata // renamed variable
instead of
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
Your ValidationWebMethod does not return anything. Make it return, for example, string.
I'm using Tagify, which is basically using jQuery Autocomplete,
references :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<script src="../../../Scripts/jquery.tagify.js" type="text/javascript"></script>
<link href="../../../Styles/jqueryTagify.css" rel="stylesheet" type="text/css" />
Script :
<script>
var myTextArea = $("#txtbox").tagify();
myTextArea.tagify('inputField').autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "Demo.aspx/GetKeyword",
data: "{'match': '" + request.term + "'}",
dataType: "json",
contentType: "application/json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item,
}
}));
}
});
},
position: { of: myTextArea.tagify('containerDiv') },
close: function(event, ui) { myTextArea.tagify('add'); },
});
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
return false;
});
</script>
HTML is :
<input type="text" id="txtbox" />
<input class="submit" type="submit" value="Get Values" />
So when we clicked on submit button, we get tags value from here
var tagStr = $("#txtbox").tagify('serialize');
and when I clicked on getvalues the result like this
How could I get those values in the Code Behind in C#?
add a hidden field in html:
<input id="hiddenTags" name="tags" type="hidden"/>
and update submit js:
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
$('#hiddenTags').val(tagStr);
return false;
});
now you can get tags in c#:
string tags = Request.Form["tags"];