I have an AJAX code where I am trying to send some data to a method within C# code-behind
I've tried to send them either using text data type and json data type, but neither of them are working with me.
when I use json type, it returns me the following error:
Internal Server Error
and when using text me
thod, there is no error appear and the code comes through the success function, but the actually the data is never sent to the method of the code-behind class
this is the ajax code using json type:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
And this is the ajax code using the text format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: sCriterion,
contentType: "application/text; charset=utf-8",
dataType: "text",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
Also here is the my code-behind method that the data should be sent to:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetSearchCritetrion(object selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
}
I've used the exact same ajax code in another project and it works perfectly, but here i'm not getting where the error is, so any suggestions please?
see if this works
instead of sending object try to pass as string
data: JSON.stringify({selectedItem : sCriterion }),
code behind
public void GetSearchCritetrion(string selectedItem)
Here is a really simple example that posts JSON to a controller method, which converts this into an object and then returns a response.
HTML:
<button id="go" class="btn">Go</button>
JS:
var obj = { foo: 123, bar: "abc " };
$('#go').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Test/TestJson',
data: JSON.stringify(obj),
success: function (response) {
alert(response.result)
},
failure: function (response) {
alert('fail');
}
});
});
Controller:
public class TestController : Controller
{
[OutputCache(Location = OutputCacheLocation.None)]
public JsonResult TestJson(TestClass tc)
{
return Json(new { result = "foo=" + tc.foo + " bar=" + tc.bar }, JsonRequestBehavior.AllowGet);
}
public class TestClass
{
public int foo { get; set; }
public string bar { get; set; }
}
}
I think this help you.
class Item
{
public int id { get; set; }
}
[WebMethod]
public static void GetSearchCritetrion(Item selectedItem)
{
//ToDo: selectedItem.id
}
Related
I am learning C# MVC using dotnetfiddle web to write code.
I have created a new project with the default code of dotnetfiddle for MVC type, but I want to display the question in the alert instead of the answer.
I want to know how to pass parameters to the controller from the view.
This is the ajax method:
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: JSON.stringify({Answer: '', Question: $('#Question').val()}),
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
And this is the controller method:
[HttpPost]
public JsonResult GetAnswer(string question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new { result = question});
}
You can check and test the code here: dotnetfiddle (Edit: it will be a good answer if it works here)
These code changes will work for you. If you wanna verify check the fiddle. DotNetFiddle
Client side Changes
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {"Answer": '', "Question": $('#Question').val()},
type: 'POST',
success: function(resp) {
openAlert(resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
Server Side Changes
[HttpPost]
public JsonResult GetAnswer(SampleViewModel model)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(model);
}
This is the method I used to pass parameters to controller
First, assign the parameter you want to pass to a variable with the value from the
input id as stated in your dotnetfiddle
var questionParam = $("#Question").val();
Then for passing it to AJAX, I think your method is already correct, this is how I do it
$.ajax({
url: '/Home/GetAnswer?question=' + questionParam ,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
This method works for me in my project, if the value is a string I think you don't need to stringify the value.
I'm still a beginner as well so maybe my method is wrong or not the best way to do it, I hope it helps you.
You are getting the value of the question in the action because your action has got a single parameter string question in there.
What you need to do is:
Send a json object from the view
In the action user a model with two properties (Answer and Question) to get the value sent by the view
Then in the action you decide what data you need to send to view
View:
Send JSON object to action:
JSON.stringify({Answer: '', Question: $('#Question').val()})
When you get the data returned from controller:
openAlert(resp.Answer);
Controller:
public JsonResult GetAnswer(MyQA model)
{
// model.Answer
// model.Question
// Your business logic goes here
return Json(new { result = model});
}
Here is the MyQA class:
public class MyQA
{
public string Answer { get; set; }
public string Question{ get; set; }
}
dotnetfiddle had a problem with this line: contentType: "application/json; charset=utf-8",
change script to :
$('.submit').click(function() {
if ($('form').valid()) {
$.ajax({
url: '#Url.Action("GetAnswer", "Home")',
data: {
Answer: '',
Question: $('#Question').val()
},
type: 'POST',
dataType: 'json',
success: function(resp) {
openAlert('Answer :' + resp.Answer + ' -----Question : ' + resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + textStatus);
}
});
} else {
closeAlert();
}
});
change action GetAnswer to :
[HttpPost]
public JsonResult GetAnswer(string Answer,string Question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new {Answer = answer,Question = Question});
}
So basically when i'm trying to make ajax call it doesn't run code behind it, no error code, everything seems fine but isnt, even after adding a breakpoint, it doesnt hit it.
Roulette Controller:
public class RouletteController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Pts(int amount)
{
System.Diagnostics.Debug.WriteLine("1111");
Console.WriteLine("2222");
return Json("test");
}
}
JS Script:
$.ajax({
type: "POST",
url: '#Url.Action("Pts", "Roulette")',
contentType: "application/json",
data: JSON.stringify({ id: "1",}),
success: function(recData) { alert('Success'); },
error: function (xhRequest, ErrorText, thrownError) {
alert("Fail");
console.log('xhRequest: ' + xhRequest + "\n");
console.log('ErrorText: ' + ErrorText + "\n");
console.log('thrownError: ' + thrownError + "\n");
}
})
#Edit
Network Tab:
Fix your ajax:
$.ajax({
type: "POST",
url: '/Roulette/Pts")',
data: { amount: 1},
success: function(recData) { alert('Success'); },
error: function (xhRequest, ErrorText, thrownError) {
alert("Fail");
console.log('xhRequest: ' + xhRequest + "\n");
console.log('ErrorText: ' + ErrorText + "\n");
console.log('thrownError: ' + thrownError + "\n");
}
});
And just for the test modify your action header
[Route("~/Roulette/Pts")]
public ActionResult Pts(int amount)
{
System.Diagnostics.Debug.WriteLine("1111");
Console.WriteLine("2222");
return Json("test");
}
Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}
When I using a literal stringified JSON object, all works as expected
Index.cshtml (with literal ajax string $.ajax WORKS)
var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';
var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
url: '/api/auditApi',
type: "Post",
contentType: "application/json; charset=utf-8",
data: '{\'Thing1\':\'42\',\'Thing2\':\'43\',\'Thing3\':\'44\'}',
dataType: 'json',
success: function (result) {
$(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoAudit").data("kendoGrid").dataSource.read();
$(".kendoAudit").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
However, when I use a serialized object created inline, it get null passed in to the post handler
Index.cshtml (with object created inline and passed to $.ajax FAILS)
var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';
var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
url: '/api/auditApi',
type: "Post",
contentType: "application/json; charset=utf-8",
data: searchSerialized, //I have tried concatenating with + '' also
dataType: 'json',
success: function (result) {
$(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoAudit").data("kendoGrid").dataSource.read();
$(".kendoAudit").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
Controller
public HttpResponseMessage Post([FromBody]string value)
{
try
{
var results = JsonConvert.DeserializeObject<dynamic>(value);
}
catch (Exception ex)
{
// throws because value is null.
}
}
I'm sure there's something abundantly obvious I'm missing in the conversion here.
The debug line: alert(searchSerialized); displays what I'm expecting
You can directly get the data into model.
When serialized object is posted (which is no more string) MVC automatically bind it to the proper model.
Now change your action method something like this.
public class SearchObject
{
public int Thing1 { get; set; }
public int Thing2 { get; set; }
public int Thing3 { get; set; }
}
[HttpPost]
public ActionResult Test(SearchObject searchObject)
{
return View();
}
I am using webmethod with Jquery. I have write a alert in success function and I got that alert when I run the project but My Webmthod did not call and So code is not work for me. I have put degub a point in Webmethod but it did not hit. I did not get any error nor my method call.
Below is my code of Jquery and Webmethod:
<script type='text/javascript' src="Scripts/jquery-1.4.1.min.js"></script>
function onDialogClosed(sender, args) {
$(document).ready(function () {
$.ajax({
type: "POST",
url: "SpellChecker.aspx/Save",
data: { DocName: $("#txttest").val() },
success: function (msg) {
alert($("#txttest").val());
},
error: function (a,b,c) {
alert(a+ b+ c);
}
});
});
}
WebMEthod :
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Save(string DocName)
{
try
{
GeneralDataTraveler objDataTraveller = new GeneralDataTraveler();
objDataTraveller.Field1 = Convert.ToString(DocName);
new ServiceCenter().SessionSetGeneralDataTraveller(objDataTraveller);
return "HEllo";
}
catch (Exception ex)
{
return null;
}
}
Try as below specifying content type, datatype and data as below format. It is working for me
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "order_form.aspx/GetAutoCompleteData",
data: '{DocName: "' + $("#txttest").val() + '" }',
dataType: "json",
success: function(data) {
//response(data.d);
alert('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Try with following:
1.Enable Webmethod to be called from Script using:
[System.Web.Script.Services.ScriptService]
2.Enable the webservice PAGE METHOD to be called on page with scripting:
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true">
</cc1:ToolkitScriptManager>
Hope this helps!