Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core - Call controller method in javascript without Ajax

I'd like to call the method "EditProject" of my controller "Project" with a parameter being the Id of the project.

I've seen many people using Ajax, but the problem is I'd like to call the controller which in turn will redirect the user to the View "EditProject", I don't want to stay on the same page

Here is the code I've tried before figuring out it doesn't work :

$('.edit-project').click(function (d) {
    var id = $(this).attr('data-projectId');

    $.ajax({
        url: '@Url.Action("EditProject", "Project")',
        data: { id: id },
        type: "GET"
    }).done(function() {
        console.log("Done");
    });
    return false;
});

I've also tried simply using

$.get("/Project/EditProject/" +id); 
window.location.href = '@Url.Action("EditProject", "Project")' + '/' + id;
window.location.href = ("/Project/EditProject/" +id);

but it returns a 404 error.

The method called is very simple :

[HttpGet]
[Authorize(Roles = "Professional")]
public async Task<IActionResult> EditProject(int id)
{
    Project p = await _unitOfWork.Projects.GetById(id);
     ViewData["Title"] = "Modification du challenge " + p.ProjectName;
     return View(p);
}

And as expected with Ajax, it does return the View, but it returns it as a response to the ajax query, and thus it doesn't redirect and show the View as I would like.

like image 662
Nenoxx Avatar asked Mar 05 '18 11:03

Nenoxx


2 Answers

You simply want to redirect there instead.

window.location.href = '@Url.Action("EditProject", "Project")' + '/' + id

There may be an MVC way to pass your id to @Url.Action but I'm not too familiar with it - string concatenation should work.

The controller is possibly not understanding what /1 means. You may have to change it to the following:

[HttpGet("{id}", Name = "EditProject")]
[Authorize(Roles = "Professional")]
public async Task<IActionResult> EditProject([FromRoute] int id)
{
    Project p = await _unitOfWork.Projects.GetById(id);
     ViewData["Title"] = "Modification du challenge " + p.ProjectName;
     return View(p);
}

This tells MVC to expect your parameter to come from the route.

like image 130
UncleDave Avatar answered Oct 21 '22 10:10

UncleDave


You can simply do this

window.location.href = '@Url.Action("EditProject", "Project",new { id = ID })';

you don't have to change your Action method routing if your default routing is alright.

like image 38
Sabir Hossain Avatar answered Oct 21 '22 08:10

Sabir Hossain