how to fix 'captcha validation is required' error in c# - javascript

After checking the i'm not a robot checkbox on validation, there's a java script alert "localhost:12345 says null" then when i click "OK" on the alert then go to click the submit button, still says "Captcha validation is required" even after i validated.
This is for my contact us page, validation won't work even after i got new keys which initially i thought were the problem.
C#
public partial class _default : System.Web.UI.Page
{
classes.Common xCommon = new classes.Common();
classes.Email xEmail = new classes.Email();
protected static string ReCaptcha_Key = "6LczL3QUAAAAAGnY8hnA-hgRjHV0q---------";
protected static string ReCaptcha_Secret = "6LczL3QUAAAAADWlVe0IKVERdq----------";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Contact_Submit_Click(object sender, EventArgs e)
{
xEmail.ContactUs_Email(txt_Contact_Name.Text, txt_Contact_Email.Text, txt_Contact_No.Text, ddl_Branch.SelectedItem.ToString(), ddl_Division.SelectedValue,ddl_Type.SelectedValue,txt_Contact_Message.Text, ddl_Branch.SelectedValue);
ltr_MessageReturn.Text = xCommon.Return_Message("contactus", "");
btn_Contact_Submit.Visible = false;
}
[WebMethod]
public static string VerifyCaptcha(string response)
{
string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + response;
return (new WebClient()).DownloadString(url);
}
}
}
JavaScript
var onloadCallback = function () {
grecaptcha.render('dvCaptcha', {
'sitekey': '<%=ReCaptcha_Key %>',
'callback': function (response) {
$.ajax({
type: "POST",
url: "default.aspx/VerifyCaptcha",
data: "{response: '" + response + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var captchaResponse = jQuery.parseJSON(r.d);
if (captchaResponse.success) {
$("[id*=txtCaptcha]").val(captchaResponse.success);
$("[id*=rfvCaptcha]").hide();
} else {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
var error = captchaResponse["error-codes"][0];
$("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
}
}
});
}
});
};
</script>
I expect the validation to pass after a user has selected all the required images to pass validation, and then submitted. but the output still says validation required.

Related

how to call method with variable from javascript

I have this code that is not running in asp.net core 3.1 I need to send a variable to the method GetClientCaseType() it give error in #Model.GetClientCaseType[myInt] myInt if i put 1 or any number it works fine while for variable it give error
function casetype(value)
{
var myInt = parseInt(value.options[value.selectedIndex].value);
var casetype |"= '#Model.GetClientCaseType[myInt]';
alert(casetype + ' = ' + myInt.toString());
$("#ClientCase_cCaseType").val(casetype);
}
in .cs page
public string GetClientCaseType(int? myInt)
{
return something;
}
Any Solution please help thanks in advance
I tried ajax with no result 'error'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebLawyer1.Data;
using WebLawyer1.Models;
namespace WebLawyer1.Pages.ClientCases
{
public class CreateModel : PopulateClientCasePageModel
{
private readonly WebLawyer1.Data.LawyerDbContext _context;
public CreateModel(WebLawyer1.Data.LawyerDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
PopulateClientInfosDropDownList(_context);
PopulateCaseTypesDropDownList(_context);
return Page();
}
[BindProperty]
public ClientCase ClientCase { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
//if (!ModelState.IsValid)
//{
// return Page();
//}
//_context.ClientInfo.Add(ClientInfo);
//await _context.SaveChangesAsync();
//return RedirectToPage("./Index");
var emptyClientCase = new ClientCase();
if (await TryUpdateModelAsync<ClientCase>(
emptyClientCase,
"clientcase", // Prefix for form value.
s => s.iClientInfoID, s => s.iCaseTypeID, s => s.cCaseType, s => s.cPart,
s => s.iSequence, s => s.cKeyCase, s => s.dDate, s => s.cTitle,
s => s.cNote, s => s.cDetail, s => s.nFees, s => s.lWinFail, s => s.lClosed))
{
_context.ClientCase.Add(emptyClientCase);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
// Select CategoryID if TryUpdateModelAsync fails.
PopulateClientInfosDropDownList(_context, emptyClientCase.iClientInfoID);
PopulateCaseTypesDropDownList(_context, emptyClientCase.iCaseTypeID);
return Page();
}
public ActionResult GetUploadedFile(int id)
{
var result = _context.CaseType.Where(x => x.iCaseTypeID == id).First();
return Json(result.cCaseType);
}
}
}
<script>
function casetype(value) {
var id = parseInt(value.options[value.selectedIndex].value);
$.ajax({
url: '#Url.Action("GetUploadedFile", "Create")',
type: "POST",
data: JSON.stringify(id),
contentType: "application/json",
datatype: "json",
success: function (data) {
if (data != null) {
var vdata = data;
$('#ClientCase_cCaseType').val(vdata.id);
}
}
});
}
</script>
Actually, you can't do this. The reason is that they do not "live" in the same time. Javascript code is available only after C# / Razor is rendered. Refer to this thread.
So, I think you should use ajax here to send a request to access GetClientCaseType() method.
Update:
For how to send a ajax post request, you need to do the below steps:
1.Add the below service in stratup.cs
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
2.Add the AntiForgeryToken to the current page
#Html.AntiForgeryToken();
3.Set the token to request header in ajax
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
This is an example:
Create.cshtml:
#page
#model RazorApp.Pages.ClientCases.CreateModel
#Html.AntiForgeryToken();
<button id="btn" onclick="casetype()">Click</button>
#section scripts{
<script>
function casetype() {
var id = 1;
$.ajax({
url: 'Create?handler=GetUploadedFile',
type: "POST",
data: { id : id },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
if (data != null) {
var vdata = data;
}
}
});
}
</script>
}
Create.cshtml.cs:
public class CreateModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostGetUploadedFile(int id)
{
var result = "AAA";
return new JsonResult(result);
}
}
Note: the pagehandler should be in this format OnPostXxx() or OnGetXxx().
And the url in ajax should like XXX?handler=Xxx.
Result:

Calling a C# method from Javascript and executing the code inside the

I have a Javascript function I am calling from C# code behind when a user clicks an OnRowDeleting call from a GridView. Here is that Call and method
OnRowDeleting="GridView1_RowDeleting"
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "Ealert();", true);
}
It then calls that JS code and asks a question to the user. Based on whether they hit yes or no. I need it the JS to send a call to a C# method. Here is the JS code and the C# code that it is supposed to call.
<script> ...JS..
function Ealert() {
//var test = document.getElementById("hdField");
bootbox.confirm({
message: "Did you send the renewal email associated with this client?",
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if (result == true) {
bootbox.alert({
message: "Thank you",
size: 'medium'
});
// document.getElementById('<%=hdField.ClientID %>').value = "true";
} else {
bootbox.alert({
message: "Please go back to your saved location\n and send the renewal email.",
size:'small'
});
// document.getElementById('<%= hdField.ClientID %>').value = "false";
PageMethods.testCSharp();
function onSuccess(result) {
alert(result);
}
function onFailure(result) {
alert("Failed!");
}
}
console.log('This was logged in the callback: ' + result);
}
});
}
C#
[WebMethod]
public static void testCSharp(bool result, GridView GridView1, object sender, EventArgs e)
{
bool variable = result;
string t = result.ToString();
MessageBox.Show(t);
string UniqClient = GridView1.SelectedRow.Cells[1].Text;
string UniqPolicy = GridView1.SelectedRow.Cells[3].Text;
string emailed = "No";
string query = "UPDATE [Reviewed_Renewal_Policy] SET [Emailed] = #emailed where where ([UniqClient] = #UniqClient) AND ([UniqPolicy] = #UniqPolicy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=GTU_Apps;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqClient", UniqClient);
comm.Parameters.AddWithValue("#UniqPolicy", UniqPolicy);
comm.Parameters.AddWithValue("#emailed", emailed);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
return;
}
The issue is the PageMethods call to this method never works. I was receiving and error that PageMethods wasn't setup correctly, but changing the method to public static void fixed it. However, it executes nothing in the method itself.
I had the SQL query commented out and used the MessageBox.Show as a test, but it doesn't work. Does anyone have any idea why or how I can have this code executed based off what option is chosen in the JavaScript? Thanks for the help
You need to use an Ajax call in order send a value to your C# function.
$.ajax({
data: formData,
method: "Post",
url: url,
processData: false,
contentType: false,
success: function (d) {
SuccessMessage(successMsg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
ErrorMessage(errorMsg);
}
});
Something similar to this. URL will be the path to your c# method.

ASP.NET MVC POST Route does not point to the correct Method

I´ve got a problem with my current mvc project.
I´m using an ajax call to send new comments to the server but the method does not even get called.
My js code:
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Threads")';
var threadId = $("#threadId").val();
var msg = $("#answer_msg").val();
alert(actionUrl);
alert(msg);
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: "Message=" + msg + "&threadId=" + threadId,
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
as you see I´ve alerted the url, msg and threadId and they are all correct. url: "/Threads/AnswerThread", msg: "test", threadId: 1.
I´ve already tried to put a breakpoint inside the AnswerThread method but it does not get called. The "AnswerThread" method is inside the "ThreadsController" and looks like this:
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
var userId = User.Identity.GetUserId();
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = Message,
PublishTime = DateTime.Now,
ThreadId = threadId,
UserId = userId
});
db.Complete();
}
return PartialView("/Views/Partial/Clear.cshtml");
}
That´s exactly the same way I did it in the backend controllers but there it just works fine.
I hope somebody can help me..
UPDATE:
Made some changes just to try if any other way works.
Change1 js:
var data = {
threadId: threadId,
Message: msg
};
$.ajax({
url: actionUrl,
type: "POST",
content: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function (msg) {
if (msg.success == true) {
hideLoadingTab();
location.reload();
}
else
{
alert("Ein Fehler ist aufgetreten: " + msg.error);
}
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
Change 2 c#:
[HttpPost]
public JsonResult AnswerThread([System.Web.Http.FromBody]PostDataModel data)
{
var userId = User.Identity.GetUserId();
string error = "";
bool success = false;
try
{
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = data.Message,
PublishTime = DateTime.Now,
ThreadId = data.threadId,
UserId = userId
});
success = true;
db.Complete();
}
}
catch(Exception ex)
{
error = ex.Message;
}
return Json(String.Format("'Success':'{0}', 'Error':'{1}'", success, error));
I tried this now with and without the "[FromBody]" statement.
Oh yes and I´ve added the DataModel like this:
public class PostDataModel
{
public int threadId { get; set; }
public string Message { get; set; }
}
and I also tried to manually configure the pointed route.
routes.MapRoute(
name: "AnswerThread",
url: "threads/answer",
defaults: new { controller = "Threads", action = "AnswerThread" }
);
The "actionUrl" variable in js get´s changed to /threads/answer but I´m always getting 500 Internal Server Error. When I put a breakpoint inside the method it does not stop at any point of the ajax call.
In the Chrome Dev Tools at the "Network" tab it says to me that there is a parameter called "id" which is null which causes to this 500 internal server error. I tried to find out more information about this but the error does not tell me where this parameter is located.
I´ve got no parameter called "id" inside this method or the data model so where does this come from?
Solution:
My Routes mapping was bad. I first mapped the route /threads/{id} and THEN did /threads/answer so when the /threads/answer got called it thought "answer" is an id so it tried to enter the "Index" method. So for my particular problem (and maybe for some other guys having the same issue) the solution was just to put the mapping of the /threads/answer route in front of the /threads/{id} route and it worked.
Please check your parameter types, in controller threadId is int type and from ajax call you are passing string type.
In Js
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Home")';
var threadId = parseInt($("#threadId").val());
var msg = "Answer message";
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: { Message: msg, threadId: threadId },
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
In Controller
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
return Json("Data");
}

What I missed in my AJAX Code?

When user select any value from drop down, then Ajax has to call server and return some values through JSON object.
Here is my Ajax code
//AJAX Security
$('#ddlSecurityLevel').change(function () {
if ($('#ddlSecurityLevel').val() !== 'None') {
$.ajax({
type: 'POST',
url: 'AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=1&ReportName=TotalSales',
contentType: 'application/json; charset=utf-8',
data: 'json',
//dataType: JSON.stringify(Data),
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
//alert("hello");
alert(result.d); // output UNDEFINED
}
function AjaxFailed(result) {
alert("Error");
alert(result.status + ' ' + result.statusText);
}
}
});
Asp.net C# code
public class GetResult
{
public string removedReportName { get; set; }
public string removedColumnNames { get; set; }
public string removedFilterNames { get; set; }
}
public partial class AjaxSecurity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string securityLevelOrUser = Request["securityLevelOrUser"].ToString();
if (securityLevelOrUser.Equals("SecurityLevel"))
{
string jsonString = js.Serialize(getResultBySecurityLevel(Request["SecurityKey"], Request["ReportName"]));
Response.Write(jsonString);
}
else
{
}
}
private GetResult getResultBySecurityLevel(string securityLevel,string reportName)
{
GetResult getResult = new GetResult();
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ReportHide,RColumnName,RFilterName FROM SecurityLevelDetails WHERE SecurityLevel=#SecurityLevel and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#ReportName", reportName);
cmd.Parameters.AddWithValue("#SecurityLevel", securityLevel);
con.Open();
SqlDataReader rd=cmd.ExecuteReader();
while(rd.Read())
{
getResult.removedReportName = rd["ReportHide"].ToString();
getResult.removedColumnNames = rd["RColumnName"].ToString();
getResult.removedFilterNames = rd["RFilterName"].ToString();
}
}
return getResult;
}
}
When I run my Asp.net code with following parameter, It returns values in browser
URL
http://localhost:55047/AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=4&ReportName=TotalSales
Response.Write
{"removedReportName":"1","removedColumnNames":"ItemLookupCode,Department","removedFilterNames":"ExtendedDescription,DepartmentName"}
But the output alert is Undefined
Comment data:'json' and Remove d from alert(result.d);
To access the data in js alert you can write like this,
function AjaxSucceeded(result) {
if(result!=null)
{
alert(result[0].removedReportName +"," result[0].removedColumnNames);
}
}
In your Page_Load method, you need to clear out the output and write your own,
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
Please check this link, this is what you need

Why doesn't my ajax call reach my .NET WebMethod?

I can't for the life of me understand why this code isn't working. I need a second set of eyes to review it - TIA:
This function returns success, but the C# method is not called.
JavaScript
$(function() {
($("#survey").on("submit", function() {
var data = serializeForm();
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert('ok');
},
error: function(data) {
alert('failed');
}
}); //ajax
return false;
}));
function serializeForm() {
var data = new Object;
$("#survey input[type='checkbox']").each(
function(index) {
data[$(this).get(0).id] = $(this).get(0).checked ? 1 : 0;
});
data.otherEnviron = $("#survey input[type='text']").val();
var strData = JSON.stringify(data);
return strData;
}
});
Revised:
$(function () {
($("#survey").on("submit", function() {
var data = serializeForm();
alert(data);
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('ok-'+ data);
},
error: function (xml, textStatus, errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
}); //ajax
return false;
}));
Note:
strData="{\"ms\":1,\"google\":0,\"PHP\":0,\"otherEnviron\":\".NET\"}"
C# WebMethod
[WebMethod]
private void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
using (SqlConnection scon = new SqlConnection(connectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
}
}
Revised C#
[WebMethod]
public static void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
try
{
using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["C287577_NorthwindConnectionString"].ConnectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
scmd.Dispose();
}
} catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
This is still not working. No error msg is shown, only ok.
because WebMethod must be public and static
Similar question: ASP.NET jQuery error: Unknown Web Method
If you need more security around your ajax call, try moving it to a web service.
public static void SaveSurveyInfo
The method should be static and public in aspx pages to be hit.
In asmx it can be just public.

Categories