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
Related
I'm sending a post request without a form in asp.net. I'm getting error 400.
AJAX
function deteleCategorieBtn(id) {
if (confirm("Are you sure you want to delete ?")) {
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
})
}
CONTROLLER
// POST: Categories/Delete/5
[Route("delete/{id?}")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var category = await _context.Categories
.FirstOrDefaultAsync(m => m.Id == id);
if(category != null){
_context.Categories.Remove(category);
await _context.SaveChangesAsync();
}
else
{
return Json(new { error = true, messages = "Categorie doesn't exist" }, new Newtonsoft.Json.JsonSerializerSettings());
}
return Json(new { success = true, messages = "Registered well" }, new Newtonsoft.Json.JsonSerializerSettings());
}
}
On the console, the url is correct
I tried changing the type from POST to DELETE in ajax part, and HttpPost to HttpDelete - Didn't work
I used the very same controller code successfully with a form that looks like that :
<form asp-action="Delete" asp-route-id="#item.Id" onclick="return confirm('Are you sure you want to delete ? ?');">
<button type="submit" value="Delete" class="btn btn-sm btn-clean btn-icon"></button>
</form>
EDIT :
Found this error message :
System.InvalidOperationException: The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations.
You need to add an Antiforgery token while doing the ajax post.
Add an antiforgerytoken like below in your page
#Html.AntiForgeryToken()
This will be added in a hidden input field
While doing the ajax post, send the token like below
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
});
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.
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.
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");
}
I have an MVC4 application, and on the layout (master page for the oldies), I have some javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
This simply logs in a user.
This is working fine.
However, on another screen I now have some new javascript, which does similar function, by taking data from a form, and passing it to a controller to handle.
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewCard').on('click', function () {
var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };
$.ajax({
url: '#Url.Action("SaveBankCard", "BankAccount")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
// window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no");
}
});
});
});
</script>
When I click the save button that this code is linked to, the code fires, the controller method goes well, the data is stored, but then, when I refresh the screen, I get an 'Undefinied' error coming from the LOGIN script above. It seems to fire when the page is reloaded. I am unsure why it's firing. It should just load, ready to fire, but it seems to be called, and fails.
The controller that it calls is this:
public ActionResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
var card = new AccountCardDto
{
Id = 0,
AccountId = accountId,
Active = active == "on",
CardHolderName = cardHolder,
CardNumber = cardNumber,
ExpiryDate = new DateTime(expiryYear, expiryMonth, 1)
};
int id = new BankAccountService().SaveCard(card);
return RedirectToAction("EditBankAccount", new { bankAccountId = accountId });
}
The problem happens on the RedirectToAction... when that view reloads, which includes the Layout, the Layout javascript fires.
EDIT: I now see that it's the btnSubmitNewCard javascript that is fired twice. Once when the click event happens (expected), and then again when the postback happens. Why is the second event happening?
Check with this: -
$('.btnSubmitNewCard').click(function () {...});
You are getting Undefined in the line that checks status:
if (result.Success == 'true') {
Because result contains string with html response of the view for the EditBankAccount action and does not have "Success" property.
You can put breakepoint in debugger and see. You can use debugger; statement as breakpoint