JQuery Ajax function not calling backend method in DNN - c#

I cannot get DotNetNuke to execute the backend code from my JQuery Ajax function.
I have the following JQuery code on my View.ascx file
I did try to change the URL to View.ascx/DeleteReviewData but no luck.
function deleteReview(ReviewID){
var ReviewIDToDelete = ReviewID;
$.ajax({
type: "POST",
contentType: "application/json",
url: "https://dnndev.me/Product-View/DeleteReviewData",
data: "{'deleteReviewID': '"+ ReviewIDToDelete +"'}",
datatype: "json",
success: function (data) {
alert("Delete successfull");
},
error: function (error) {
alert(error);
}
});
}
This is my back-end code which doesn't get executed on the View.ascx.cs file:
[System.Web.Services.WebMethod]
public static void DeleteReviewData(int deleteReviewID)
{
try
{
//Deletes a review from the database
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()))
{
connection.Open();
using (SqlCommand command = new SqlCommand($"delete from ProductReviews where ReviewID = {deleteReviewID}"))
{
command.Connection = connection;
command.ExecuteNonQuery();
}
connection.Close();
}
}
catch(Exception ex)
{
throw;
}
}
If I should use MapHttpRoute. Does someone have an example, please?
I looked at the following post, but I am not sure about using RouteConfig.cs and extra headers and etc: https://www.dnnsoftware.com/answers/execute-an-action-by-calling-an-ajax-post
I currently get no Console errors. It goes to the success section.
When I hover over Type, ContentType or any one of those while debugging it says not defined. See example below. The site is using JQuery 01.09.01
2nd image
UPDATE
I have changed the URL which now gives me a 404 error: url: $.fn.GetBaseURL() + 'DesktopModules/ProductDetailedView/DeleteReviewData'
I also tried this URL path with adding API API/DeleteReviewData , but I get a [object Object] error as it shows a 404 error in the console.

This is an example:
$.ajax({
data: { "Id": IdToDelete },
type: "POST",
dataType: "json",
url: "/DesktopModules/{API-ProjectName}/API/Main/DeleteExpenseByID"
}).complete(function () {
//...
});
Api method:
[HttpPost]
[DnnAuthorize]
public void DeleteExpenseByID(int Id)
{
//...
}
You need to send a number so you dont need the "'" surrounding ReviewIDToDelete var.
Also check DeleteReviewData for a [POST] attribute, it seems to be a [GET] call.

Related

Finding it impossible to post simple ajax

I am realy struggling with this and would apprecate any advice.
I have this field
<input id="scanInput" type="text" placeholder="SCAN" class="form-control" />
For which I would like to make an ajax call when the field changes, so I tried
<script>
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=GetPartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
</script>
Where my PageModel has this method
[HttpPost]
public IActionResult GetPartDetails()
{
return new JsonResult("hello");
}
and the url for the page in question is /packing/package/{id}
Now when I change the input value, I see ye on the console, and I can see that the network called http://localhost:7601/Packing/Package/40?handler=GetPartDetails (the correct URL I think?) with status code 200
But My breakpoint in GetPartDetails never hits, and I don't see yay? in the console.
I also see this message from the fail handler:
Request Failed: parsererror, SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data
But I'm not even passing any JSON data... why must it do this
I also tried this way :
$.ajax({
type: "POST",
url: "?handler=GetPartDetails",
contentType : "application/json",
dataType: "json"
})
but I get
XML Parsing Error: no element found
Location: http://localhost:7601/Packing/Package/40?handler=GetPartDetails
Line Number 1, Column 1:
I also tried
$.ajax({
url: '/?handler=Filter',
data: {
data: "input"
},
error: function (ts) { alert(ts.responseText) }
})
.done(function (result) {
console.log('done')
}).fail(function (data) {
console.log('fail')
});
with Action
public JsonResult OnGetFilter(string data)
{
return new JsonResult("result");
}
but here I see the result text in the console but my breakpoint never hits the action and there are no network errors..............
What am I doing wrong?
Excuse me for posting this answer, I'd rather do this in the comment section, but I don't have the privilege yet.
Shouldn't your PageModel look like this ?
[HttpPost]
public IActionResult GetPartDetails() {
return new JsonResult {
Text = "text", Value = "value"
};
}
Somehow I found a setup that works but I have no idea why..
PageModel
[HttpGet]
public IActionResult OnGetPart(string input)
{
var bellNumber = input.Split('_')[1];
var partDetail = _context.Parts.FirstOrDefault(p => p.BellNumber == bellNumber);
return new JsonResult(partDetail);
}
Razor Page
$.ajax({
type: 'GET',
url: "/Packing/Package/" + #Model.Package.Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
input: barcode,
handler: 'Part'
},
success: function (datas) {
console.log('success');
$('#partDescription').html(datas.description);
}
});
For this issue, it is related with the Razor page handler. For default handler routing.
Handler methods for HTTP verbs ("unnamed" handler methods) follow a
convention: On[Async] (appending Async is optional but
recommended for async methods).
For your original post, to make it work with steps below:
Change GetPartDetails to OnGetPartDetails which handler is PartDetails and http verb is Get.
Remove [HttpPost] which already define the Get verb by OnGet.
Client Request
#section Scripts{
<script type="text/javascript">
$(document).ready(function(){
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=PartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
});
</script>
}
You also could custom above rule by follow the above link to replace the default page app model provider

jQuery AJAX always executing error: {}

I'm working on a webapplication, ASP.Net MVC 4.0 with entityframework 6.0, trying to update database as per user selection. Data is sent to controller's action using jQuery AJAX. Below given is C# code to update entity which in turn updates database.
public void modidyProduct(Productdetail prodData)
{
try
{
using (SampleTrialEntities entity = new SampleTrialEntities())
{
var data = entity.Productdetails.Where(p=>p.ProductID == prodData.ProductID).FirstOrDefault<Productdetail>();
data.ProductName = prodData.ProductName;
data.ProductNumber = prodData.ProductNumber;
data.CategoryName = prodData.CategoryName;
data.ModelName = prodData.ModelName;
entity.Entry(data).State = System.Data.Entity.EntityState.Modified;
entity.SaveChanges();
}
}
catch (Exception)
{}
}
And here's jQuery AJAX call for that controller action method.
function updateProduct() {
var productData = {
ProductName: $('#prodName').val().trim(),
ProductNumber: $('#prodNum').val().trim(),
CategoryName: $('#ctgryName :selected').text(),
ModelName: $('#mdlName :selected').text(),
ProductID: atob($('#editProductId').val())
};
debugger;
$('#divLoader').show();
$.ajax({
url: '#Url.Action("modidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function (jqXHR) {
//Below line will destroy DataTable - tblProducts. So that we could bind table again. next line - loadData();
$('#tblProducts').DataTable().destroy();
$('#divLoader').hide();
loadData();
$('#addModal').modal('hide');
$('#editProductId').val('');
},
error: function (msg) {
debugger;
$('#editProductId').val('');
$('#divLoader').hide();
alert(msg);
alert("What's going wrong ?");
//alert(jqXHR.responseText);
}
});
}
After executing jQuery AJAX method & controllers action, successfully updates the record in database. Response statuscode - 200 & Status - OK is returned. But only error: { }, code block is executed every time in AJAX method.
Debugging screen capture with status-OK; statuscode - 200
This part of your $.ajax method call
dataType: 'json',
It tells jQuery that, the ajax call code is expecting a valid JSON response back but currently your server method's return type is void. That means it won't return anything and the $.ajax method is trying to parse the response (assuming it is a valid JSON), and hence getting the typical "parsererror"
When the datatype is json and the response is received from the server, the data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected.
The solution is to simply remove the dataType property in the call.
$.ajax({
url: '#Url.Action("modidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
contentType: 'application/json;charset=utf-8'
}).done(function() {
console.log('Success');
})
.fail(function(e, s, t) {
console.log('Failed');
});
Or you can update your server action method to return a json response.
[HttpPost]
public ActionResult ModidyProduct(Productdetail prodData)
{
try
{
//to do : Save
}
catch (Exception ex)
{
//to do : Log the exception
return Json(new { status = "error", message=ex.Message });
}
return Json(new { status="success"});
}
Now in your client side code, you can check the json response to see if the transaction was successful
$.ajax({
url: '#Url.Action("ModidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
}).done(function (res) {
if (res.status === 'success') {
alert('success');
} else {
alert(res.message);
}
console.log('Success');
}).fail(function(e, s, t) {
console.log('Failed');
});
You do not need to necessarily specify the dataType property value. If nothing is specified jQuery will try to infer it based on the mime type of the response coming back, in this case, the response content type will be application/json; charset=utf-8. So you should be good.

How to obtain checked checkbox values on the serverside in c# from an ajax Http POST using web forms (not MVC)?

Here's my ajax call:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
console.log($(this).prop("name") + "=" + $(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default",
type: "POST",
dataType: "json",
data: { filterValues: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
And my server side code:
public partial class tools_oppy_Default : System.Web.UI.Page
{
...
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
string checkedBoxes = Request["filterValues"];
testLabel.Text = checkedBoxes;
}
I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. However, I'm having trouble obtaining the URL. The string checkedBoxes is supposed to hold a query string like name=value&name=value&name.... but when I test it, the testLabel doesn't show anything. I'm using web forms app, not MVC. Also, I'm new to ajax and their behavior. Thanks.
First, I assume that the url in you JQuery call is valid as there is not aspx extension their.
Second, It looks like what you need to do is create a web method and call it from JQuery for example the following is a web method that accept string
[WebMethod]
public static string GetData(String input)
{
return DateTime.Now.ToString();
}
and you can call it using the same way with your current code just update the url parameter to include the method name
url: "PageName.aspx/MethodName",
for more details about web methods and their union with JQuery please check this article
Edited The following is complete sample
The web method should look like the following one
[WebMethod]
public static string GetData(string filterValues)
{
return filterValues; //This should be updated to return whatever value you need
}
The client side part of calling the web method should look like the following
$.ajax({
url: "/Default/GetData",
type: "POST",
contentType: "application/json; charset=utf-8", //I have added this as "contentType" parameter represents the type of data inside the request meanwhile the "data" parameter describes the data inside the response
data: "{ filterValues:\"" + filterCheckboxes + "\"}", //Note that I have updated the string here also set the name of the parameter similar to the input of the webmethod
dataType: "json",
success: function (result) {
alert(result.d);//You should access the data using the ".d"
}
});
One last thing, If you are using asp.net permanent routing the above code will not work and you should disable it by updating the file "App_Code/RouteConfig.cs" From
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
And remember to clear browser cache after the above update

Using jquery Autocomplete on textbox control in c#

When I run this code I get alert saying Error.
My Code:
<script type="text/javascript">
debugger;
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'fname':'" + document.getElementById('txtCategory').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select fname from tblreg where fname LIKE '%'+#CategoryText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#CategoryText", CategoryName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["fname"].ToString());
}
return result;
}
}
}
I want to debug my function GetAutoCompleteData but breakpoint is not fired at all.
What's wrong in this code? Please guide.
I have attached screen shot above.
You need to change the data property's value of you $.ajax() call to correctly reflect the C# method parameter i.e. change this line
data: "{'fname':'" + document.getElementById('txtCategory').value + "'}",
to
data: "{'CategoryName':'" + document.getElementById('txtCategory').value + "'}",
The data property should match the parameter in the signature of the action method.
You need to add [WebMethod] attribute over your method. so your method will look like this
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
....
How to use web method link
Edit 1
In your jQuery where you have written url: "GetAutoCompleteData", you need to specify the class or page name and then method name.
You cann't directly call Method you need to use the class (.aspx page) and then method.

ASP.Net MVC 3 Ajax query not firing

I have a very simple ajax call to refresh some data on my webpage, but it doesn't seem to fire correctly. The data that the call brings back is the same everytime even if the underlying data changes.
The ajax call looks like this:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
My controller looks like this:
public ActionResult ListByAjax(int Id)
{
var list = db.Address.Where(i => i.Person_Id == Id);
return PartialView("_List", list.ToList());
}
Try setting the cache to false in your ajax call - that will force the browser to send the request through to the controller:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
cache: false,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
Use
ajaxSetup({ cache: false }); });
This turns off caching for all ajax calls made by your app.

Categories

Resources