I am trying to edit a field after clicking an item from a table.
I added an on clcik event to every object in the table like this :
onclick="itemEdit(this)
And my javascript function looks something like :
function itemEdit(e) {
console.log($(e).attr("id"));
var itmId = $(e).attr("id");
$.ajax({
url: '#Url.Action("Index", "Scraping")',
data: {itemId: itmId},
type: 'POST',
success: function(data) {
alert(data);
}
});
}
And what I do in my Index method is to load the clicked item in a more detailed manner on the top of the page like this :
public ActionResult Index(string itemId)
{
if (itemId != null)
{
im.loadItem(itemId.ToString());
}
else
{
if (im.lstEditModel.Count == 0)
{
im.loadLists();
}
}
return RedirectToAction("Index");
}
The problem I am having is that whenever I click an item, the index method executes twice..and thus creating a mess. Any help?
I don't see an [HttpPost] mark on that method, but at the end of the method, you are redirecting to another Index action... you normally would return some sort of JSON data rather than return RedirectToAction("Index");... this statement would be doing what you are describing, calling your Get Action.
From MSDN:
Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
Try to stop event bubbling.
function itemEdit(e) {
e.stopPropagation();
console.log($(e).attr("id"));
var itmId = $(e).attr("id");
$.ajax({
url: '#Url.Action("Index", "Scraping")',
data: {itemId: itmId},
type: 'POST',
success: function(data) {
alert(data);
}
});
}
Please ignore this, by mistake I forgot to put href="#" when adding the onClick event causing the browser to reload my javascript code. I had typed href=""
Related
I have a datatable that gets values from a database with on every line on the last column a delete button.
$"<button type='submit' class='btn btn-danger test' id='{i.id}' onclick='return Delete();'>Delete</button>"
My button gets an id which is the id of the model from that row.
I want to delete the row if I click on the button.
But can't figure out how to call the method without my application trying to find the view. (I have no delete view and don't want to make one).
I've looked it up but nothing works.
My controller action :
[Authorize(Roles = "user")]
[HttpDelete]
public ActionResult Delete(Guid id)
{
if (BLayer.getAllGames().ToList().Exists(x => x.id == id))
{
BLayer.DeleteGame(id);
}
return new EmptyResult();
}
My Jquery function :
function Delete() {
var table = $("#tableOverviewGames").DataTable();
$('#tableOverviewGames tbody').on('click', 'button', function () {
var idGame = $(this).attr('id');
$.ajax({
url: "Delete",
type: 'DELETE',
data: { id: idGame },
async: false,
contentType: false,
success: function (data) {
alert("Vous avez supprimé le jeu");
},
error: function (data) {
console.log(data);
}
});
});
}
Can someone help me please?
Thanks!
EDIT:
This is the error I get in the console :
DELETE http://localhost:3673/Game/Delete 404 (Not Found)
Why dont you just return a JSON from the controller such as
return Json(new {success = true})
and then you can (if you need to) do checks in the ajax success against whether or not it worked
I see that when you make the call you're passing wrong Uri, thats why you got 404 NOT FOUND.
Change your HttpDelete attribute as
[HttpDelete("{id}")]
pass the guid as part of Uri like http://localhost:3673/Game/eef63296-6bb3-40a5-aa89-be69e75a66eb, also any body passed for delete calls will be ignored unless Content-Length header is added, check this link.
If you still insist on a body, try changing signature as shown below
[Authorize(Roles = "user")]
[HttpPost("delete")] //Added route to differentiate Create/Insert REST end point
public ActionResult Delete([FromBody]Guid id)
Your AJAX call should be like
$.ajax({
url: "Delete",
type: 'DELETE',
data: idGame, // Pass value directly.
sync: false,
contentType: false,
success: function (data) {
alert("Vous avez supprimé le jeu");
},
If I were you, I'd start testing with basic type like string for fields that cause trouble.
I'm working with an asp.net MVC project. A coworker was new to MVC and handled all of the populating of data and click actions by using ajax calls. I know this isn't how MVC should be set up, but it's what I'm stuck with. I'm just trying to work around that the best I can. Anyway, within the method the ajax goes to, I need to redirect the user to a new page. How do I do that?
I tried Response.Redirect, but I got an error saying it didn't exist. I tried to add a using class, but couldn't it to work.
I found System.Diagnostics.Process.Start, but it opens in a new browser tab. Could there possibly be a way to open in the same tab?
So here's the ajax call. This is triggered in a javascript function when the user clicks a button:
$.ajax({
contentType: "application/json",
dataType: "json",
type: "post",
url: "/api/WoApi/PostWoApprGen/" + vUsr,
data: JSON.stringify(invObj),
success: function (res)
{
if (res)
{
var inv = $('#DivInv');
inv.html(res);
output = $('#TmpMsg');
output.html("");
opStatMsg("success", "rptGenWin");
}
else
{
opStatMsg("error", "rptGenWin");
}
}
});
That goes to a class in the controller directory, filename WoApiController.cs:
public string PostWoInv([FromBody] Koorsen.OpenAccess.WrkOrdTemp obj)
{
var currentUser = ClsUtility.GetCurrentUser();
if (currentUser == 0)
{
rep.UpdateWorkOrderStatusInvoiced(obj.WoTempId, currentUser, obj);
}
else
{
System.Diagnostics.Process.Start("~Admin/Login");
}
.............
.............
In your success callback, simply do
location.href = 'Home/Index';
or, preferably, using Razor and a method called Index in HomeController
location.href = '#Url.Action("Index", "Home")';
I tried many ways and it's still not working... I'm calling controller's method with ajax call. Thanks to answer to my previous question it's working fine, I have data that I wanted to send from view in controller (in CreateIncident method). Problem is that controller should render new view and redirect to it, but it's not happening. For now I just want to see new view, nothing else, I'll deal with recieved data later. Any idea why is this happening? Is this because I'm calling method with ajax and not by e.g. simple Url.AcionLink?
Ajax call to method:
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location)
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data}
})
}
Controller:
public ActionResult Create()
{
Incident newIncident = new Incident();
newIncident.AddDate = DateTime.Today.Date;
newIncident.DateOfIncident = DateTime.Today.Date;
newIncident.TimeOfIncident = DateTime.Today.TimeOfDay;
return this.View(newIncident);
}
[HttpPost]
public ActionResult CreateIncident(string JsonStr)
{
// RedirectToAction("Create"); //none of this three is working
// return View("Create");
return Redirect("Create");
}
No matter if I'm trying to access CreateIncident or Create the method is called, but there's no redirect to /Incidents/Create (I'm calling from Home/Index). Any ideas why? I would like to redirect to Create.cshtml straight from CreateIncident so I wouldn't have to pass data between methods, but any solution will do fine.
The redirect in that case has to be done through you AJAX call. Call your action method and do your logic, then redirect on success.
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data} ,
success: function (data) {
window.location.href = "Incidents/Create";
}
})
try:
url:"../Incidents/CreateIncident"
put in $ajax call error handling and see the error, it will help you
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data},
success: function(result){
// Do stuff
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
Use the view's full path instead of its name.
return View("/Incidents/Create");
Yes redirecting page in success event of ajax call is the only solution, as you are making ajax call not submitting a form. Browser redirects automatically after post only if you are posting a form.
However you can use following code if you don't want to redirect it in
success event.
function postData(url, allData){
form = document.createElement('form');
for(data in allData)
{
var input = document.createElement('input');
input.type = 'text';
input.name = data;
input.value = allData[data].toString();
form.appendChild(input);
}
form.method = 'post';
form.action = url;
form.submit();
}
and use this function like this :
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location);
postData('/Incidents/CreateIncident', {JsonStr : data})
}
warning : haven't tested :).
I'm trying to post data into a controller but it doesn't seems to work, I need the post to include the content of the view into a div when done but I cant quite achieve it
Here's my js function:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: "Student/Schedule",
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').load(a);
}
});
}
And, here's my controller:
public ActionResult Schedule(String number)
{
return View(number);
}
I am a noob in MVC and C#, so any help is welcome.
There are somethings that you should fix to solve the problem.
Change Url to "/Student/Schedule"
You are using "Student/Schedule" as url, so you are trying to call an action named "Student".
Add [HttpPost] to your action.
You should return PartialView("Schedule", number);.
When you use return View(number) it uses the string value of number as your view name. You should explicitly pass view name and model.
Use $('#schedule').html(a);
It's better to add an error function to your ajax call to be able to find errors:
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
//or you can put jqXHR.responseText somewhere as complete response. Its html.
}
Your action should return a Partial View, not a View.
Change your action to:
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number)
{
return PartialView("_Schedule", number);
}
Then, you'll need to create a partial view named _Schedule.cshtml.
Also, you need to change $('#schedule').load(a); to $('#schedule').html(a); And, I'd suggest that you use a Url.Action to set your url in your ajax call, like this:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: '#Url.Action("Schedule", "Student")',
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').html(a);
}
});
}
I had the same issue what i did was adding jquery.unobtrusive-ajax.js to my scripts
I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});
Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});