Click here to Skip to main content
14,921,361 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My Controller

[Route("api/[controller]/[action]")]
   [ApiController]
   public class UserController : Controller
   {
       private readonly IUserRepository _userRepository;

       public UserController(IUserRepository userRepository)
       {
           _userRepository = userRepository;
       }

       [HttpGet]
       public JsonResult Get()
       {
           var users = _userRepository.GetAllSync();
           return new JsonResult(users);
       }

       [HttpPost]
       public JsonResult Add([FromBody]User user)
       {
           if (!new UserSpecification().IsSatisfiedBy(user))
           {
               throw new ArgumentException("User not valid.");
           }
           if (_userRepository.AnySync(x =>
               x.Email == user.Email ||
               x.UserName == user.UserName))
           {
               throw new ArgumentException("User email or username already taken.");
           }
           _userRepository.AddSync(user);
           return new JsonResult(new { success = true, responseText = "User successfully added!" });
       }

       [HttpPatch]
       public JsonResult Change(string id, [FromBody]User user)
       {
           _userRepository.ReplaceOneSync(id, user);
           return new JsonResult(new { success = true, responseText = "User successfully modified!" });
       }

       [HttpDelete]
       public JsonResult Delete(string id)
       {
           _userRepository.DeleteSync(x => x.Id == id);
           return new JsonResult(new { success = true, responseText = "User successfully deleted!" });
       }
   }


What I have tried:

My View

<div class="text-center">
    <h1 class="display-4">Users</h1>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Username</th>
                <th>E-mail</th>
                <th>Phone</th>
                <th>Address</th>
                <th>Edit</th
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var user in Model.Users)
            {
                <tr class="user" data-userid="@user.Id">
                    <td>@user.Name</td>
                    <td>@user.UserName</td>
                    <td>@user.Email</td>
                    <td>@user.PhoneNumber</td>
                    <td>@user.Address</td>
                    <td><a class="btn btn-lg" asp-route-userId="@user.Id" asp-controller="Home" asp-action="CreateUser">class="glyphicon glyphicon-edit"></a></td>
                    <td><a class="btn btn-lg" asp-route-id="@user.Id" asp-controller="Home" asp-action="Delete" onclick="return confirm('Are you sure')">class="glyphicon glyphicon-trash"></a></td>
                    <form method="post" >
                        <td><button type="submit" asp-route-id="@user.Id" asp-controller="Home" asp-action="Post">class="glyphicon glyphicon-trash"></button></td>
                    </form>
                    <form>
                        <td> <a onclick="callDelete(@user.Id)">class="glyphicon glyphicon-trash"></a></td>
                    </form>

                    
                    



                    @*<form method="delete" action="Home/Delete/{{user.id}}">
                        <td><button type="submit">class="glyphicon glyphicon-trash"></button></td>
                    </form>
        <td>
            <button id="btnDelete" type="submit">class="glyphicon glyphicon-trash"></button>
            <script>
                $('#btnDelete').click(function () {
                    $.ajax({
                        url: '@Url.Action("Delete", "Home",@user.Id)',
                        data: { Id: $("#txtName").val() },
                        type: 'Delete',
                        success: function (data) {
                            $("#divContent").html(data);
                        }
                    });
                });
            </script>
        </td>*@
        @*@using (Html.BeginForm("Delete","Home",@user.Id,FormMethod.Get));
                    <form method="post">
                        <td><button type="submit">delete</button></td>

                        @using (Html.BeginForm("Delete", "Home"){
                        @Html.HttpMethodOverride(HttpVerbs.Delete)
                        }
                            </form>*@
                </tr>
            }
        </tbody>
    </table>
    <div id="divContent"></div>
    <a class="btn btn-primary">Add New</a>
    <div id="userModal">

    </div>


</div>
<script>
    function callDelete(id) {
        var cuisines = ["Unknown", "Mexican", "Italian", "Indian"];

        $.ajax("/Home/Delete/" + id,
                { method: "DELETE" })
            .then(function(response) { $("#divContent").text = response.text; });
    };
</script>
Posted
Updated 31-Aug-20 8:06am

1 solution

1. Get PostMan -- https://www.postman.com/downloads/[^]

2. Set it up so you can send a Delete to your controller
That will look something like this snapshot: https://i.stack.imgur.com/YIJKz.png

I don't know what port yours will be running on, but notice the URL looks like:
https://localhost:4995/User?id=1

That will hit your UserController and since the method is set to Delete and you have a default Delete action then your Delete method will be hit.

From there, you'll better be able to determine how to send a HTTP Delete to your web site. You can also check out my article here on CP : .NET Core Web API: The Least You Need To Know (Part 1 of 2)[^]


Part 2 -- Using XHR (XMLHTTPRequest)

JavaScript
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", transferComplete);
xhr.addEventListener("error", transferFailed);
var url = "https://localhost:4995/User";

function deleteUser(){
       xhr.open("DELETE", url);  // sets the HTTP VERB
       var userData = {"id":1};
       
       console.log(userData);
       xhr.setRequestHeader("Content-Type", "application/json");
       xhr.send(JSON.stringify(userData));
   }
   
v3
Comments
Mohamed Hamed 31-Aug-20 14:27pm
   
thanks a lot but my main problem is how to Call an HttpDelete action on my webapi (that return JSONResult) from an MVC View not calling it form PostMan
raddevus 31-Aug-20 15:12pm
   
check out part 2 (added to my answer above) - what you're wanting to know how to do is set up the XMLHTTPRequest XHR so you can post to the controller, it was in part 2 of my articles: https://www.codeproject.com/Articles/5268710/NET-Core-Web-API-The-Least-You-Need-To-Know-Part-2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900