Execute web controller action without view [c#] - c#

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.

Related

Asp .net core project: Ajax call can't reach controller (400 status code)

I'm refactoring my ASP .net core project and I want to make use of some Ajax calls, but I'm facing the following problem: when I try to send a request to a method in a controller of my project but it doesn't work.
I have a modal with the following button:
<button onclick="reviewRestaurant(#item.RestaurantId)" class="btn btn-outline-primary">Add review</button>
the reviewRestaurant() function looks like this:
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let review = $('textarea').val();
let data = { restaurantId, rating, review };
$.ajax({
type: "POST",
url: `/Restaurants/Review`,
data: JSON.stringify(data),
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
And the method that I wanna call in the Restaurants controller looks like so:
[Authorize]
[HttpPost]
public async Task<IActionResult> Review(int restaurantId, string rating, string content)
{
var username = this.User.Identity.Name;
await this.restaurantsService.Review(restaurantId, username, rating, content);
return this.RedirectToAction("Details", new { id=restaurantID });
// the output of this method will be refactored later once I manage to get to it
}
The problem is I cannot reach the Review method in the controller. I get the 400 status code and I don't know how to fix it. I tried using DTO and [FormData] attribute for the method parameters and tried passing the data without stringifying it still nothing works.
If anyone can help me I would be very grateful. I'm relatively new to ajax calls and simply cannot see where my mistake is.
You can try this solution:
Create a common class for your parameters (int restaurantId, string rating, string content) and use FromBody. => Review([FromBody] YourClassName)
And write this parameters in your ajax code.
contentType: 'application/json; charset=utf-8',
data: 'json'
I hope it will help you.
Here is a working demo which I test.
#section Scripts
{
<script>
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let content = $('textarea').val();
let data = { restaurantId, rating, content };
$.ajax({
type: "POST",
url:'/Restaurants/Review',
data: data,
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
</script>
}

How to get value from controller back to $.Ajax

My setup: asp.net mvc web app
I am having trouble getting a value from a controller back to the $.Ajax call (see below). The controller deletes a record in a database and counts some other records.
$.ajax({
type: "POST",
url: actions.action.RemoveItem + "?id=" + dataId,
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function (result) {
alert(result);
},
error: function (result) {
alert("Error");
}});
[HttpPost]
public JsonResult RemoveItem(int id)
{
... delete a record in the db
itemsCount = .... counts of some other records in the db
if (deletedRecord.id != null)
{
return Json(new { itemsCount });
}
else
{
return JsonError();
}
}
The ajax call and the controller work properly, however when I try to use the returned value in the success function, the alert(result) gives [object object].
I have looked through all related posts, but could not find a solution that worked. Could someone give me a hint where the problem could be and how to make it work?
Thank you in advance and regards, Manu
Result is a javascript object so alert works properly. If you want to alert it's structure as JSON use JSON.stringify() method like this:
alert(JSON.stringify(result));
If you want to access your itemsCount, just use dot or bracket notation:
alert(result.itemsCount);
alert(result['itemsCount']);

How to move between MVC controllers using knockout.js?

I have an issue with moving from one MVC controller to another. I am new to MVC/Knockout combination and trying to find a best way.
I have a HomeController that does some login processes. The Login view, of the controller, contains knockout script that posts data it. After a certain select is chosen this code is executed by a button press with data-bind="clicked: SubmitLocation"
self.SubmitLocation = function () {
var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));
alert(jsonData);
$.ajax({
ur: '#Url.Action("Login", "Home")',
type: 'post',
data: jsonData,
contentType: 'application/json',
success: function () { }
});
This brings it to the code inside MVC controller :
[HttpPost]
public ActionResult ....{
return RedirectToAction("Products", "Product");
...}
Debugging through the code, I see that it makes it over to the Product controller and even to the Products view, without exceptions. However the page on the browser itself remains on the original HomeController/Login view. Where am I going wrong?
I have also tried returning a different view from the same HOmeController instead of RedirectToAction, and it is still the same.
You can't return RedirectToAction() or return View() to an ajax call. Upon successful login, return Json(true) from the controller and in the success callback of ajax, redirect to the Products action
[HttpPost]
public ActionResult Login(UserViewModel user)
{
// authentication code here
return Json(true);
}
JS:
self.SubmitLocation = function() {
var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));
$.ajax({
ur: '#Url.Action("Login", "Home")',
type: 'post',
data: jsonData,
contentType: 'application/json',
success: function(data) {
if (data)
location.href = '#Url.Action("Products", "Product")'; // redirect
}
});
}

Ajax post not working MVC 5

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

POST and GET executing simultaneously in MVC 4

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=""

Categories

Resources