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

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.

Related

Message from stored procedure to alert box in view

I am sending parameters to a stored procedure and the stored procedure return a message back, it's either a success or an error.
public IActionResult Index() => View();
public async Task<IActionResult> Upload(IFormFile file)
{
int cmdResponse = Convert.ToInt32(cmd.Parameters["#response"].Value);
string cmdMessage = cmd.Parameters["#message"].Value.ToString();
if (cmdResponse == 0)
{
con.Close();
return RedirectToAction("Index", Json(new { status = "error", message = cmdMessage }));
}
return RedirectToAction("Index", Json(new { status = "success", message = cmdMessage }));
}
and here is the view with the Javascript where I try to display the message from the stored procedure in an alert box.
<script>
$(function () {
$("#btn").click(function () {
dangerResponseMessage('btn');
});
});
function dangerResponseMessage(result) {
var url = window.rootUrl + 'Upload/Upload';
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function (result) {
alert(result.message);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(result.message);
}
});
}
</script>
The problem is that the alert box displays undefined
and when I dismiss the alert, it return the message from the stored procedure in the URL in the browser.
The cyrillic sentence in the URL is the message I am trying to display in the alert box.
The ajax call is without data, since I don't need to send anything from the view to the controller.
Any ideas as why is it showing the message in the URL and not in the alert box?
Have you tried just console.log(result) to just confirm exactly what you're getting back? If you're code in failing in 'error', then does 'result exist? Looks like it belongs to 'success' which may also be why it's failing and showing up on the address bar.

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

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.

ASP.NET MVC redirect to login page after session expires in AJAX

I just learning ASP.NET MVC and newbie in it so I can't find the solution for some problem. Maybe somebody faced this problem and can give me advice? Thanks for all!
In my project, I use ASP.NET Identity for authorization.
The only problem I faced is how to redirect the user to login page after session expires. If action from controller called not from AJAX it works well, but if action called from AJAX function it crashes. I search for the solution, but everything I found not working for me.
Now my code looks like:
Startup.cs
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Login"),
LogoutPath = new PathString("/Home/Login"),
ExpireTimeSpan = TimeSpan.FromMinutes(1),
});
}
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="1" />
</authentication>
</system.web>
Function from JS wich calls action:
function click(d) {
//Some logic
$.ajax({
url: '#Url.Action("GetDataForNode", "Home")',
type: 'POST',
dataType: 'json',
cahe: false,
data: { uid: d.id, index: index, nodesUid: nodesUid, request },
success: function (results) {
//Some logic
},
error: function (xhr) {
if (xhr.status === 401) {
window.location.href = xhr.Data.LogOnUrl;
return;
}
}
})
}
And in controller I created:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new JsonResult
{
Data = new
{
Error = "NotAuthorized",
LogOnUrl = FormsAuthentication.LoginUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
After executed I get this
Add a life cycle method Application_EndRequest handler to your code in global.asax.cs. Every request will end in this method, This method will allows you to redirect to appropriate action, when your request is unauthorized(401) just redirect to appropriate action.
protected void Application_EndRequest()
{
// redirected to the login page.
var context = new HttpContextWrapper(Context);
if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 401)
{
new RedirectResult("~/Account/Login");
}
}
}

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");
}

Ajax call not done after a click on a button

When a user click on a button, i display a dialog box to confirm it action and after i do a delete on the server
#RequestMapping(method = RequestMethod.GET, value = "/secure/admin/deleteuser/{username}")
public String deleteUser(Model model, #PathVariable("username") String username, BindingResult result) {
...
}
$("#deleteUserConfirm").dialog({
autoOpen: false,
resizable: false,
height: 180,
modal: true,
buttons: {
"Delete user": function() {
var username = $(this).data('username');
var url = "/secure/admin/deleteuser/" + username;
//server call to delete this user
$.ajax({
type: "GET",
url: url
}).done(function() {
alert("second success");
}).fail(function() {
alert("error");
}).always(function() {
alert("finished");
});
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
i never go to the server... i see second success alert and finished alert
i don't have any error
i tried on the server
#RequestMapping(method = RequestMethod.GET, value = "/secure/admin/deleteuser")
public String deleteUser(Model model, #RequestParam("username") String username, BindingResult result) {
}
in js
$.ajax({
type: "GET",
url: "/secure/admin/deleteuser",
data: {username: "RenewalRate2"}
}).done(function() {
alert("second success");
}).fail(function() {
alert("error");
}).always(function() {
alert("finished");
});
i see in chrome a request to:
`http://localhost:8084/secure/admin/deleteuser?username=RenewalRate2`
in it's status it's 200... but nothing is done on the server.....
It might be a case of browser caching. Firefox might be showing status as 200 but request nevergets out of browser, try to append a dummy parameter at the end and then see the results.
Use confirm dialog.
var status = confirm("Are you sure??");
if(status == true)
{
//Make an ajax call and delete
}
else
{
//Do nothing.
}
i changed controller for
#RequestMapping(method = RequestMethod.GET, value = "/secure/admin/deleteuser")
#ResponseBody
public void deleteUser(#RequestParam("username") String userName) {
}
and that work file

Categories