Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript url action in razor view

I have a javascript method onRowSelected wchich gets rowid. How to pass the rowid in certain action of a controller with HttpGet?

function onRowSelected(rowid, status) {
        alert('This row has id: ' + rowid);
        //url: @Action.Url("Action","Controller")
        //post:"GET"
        // Something like this?
    }
like image 877
nebula Avatar asked Jul 22 '12 11:07

nebula


1 Answers

If your controller action expects an id query string parameter:

var url = '@Url.Action("Action", "Controller")?id=' + rowid;

or if you want to pass it as part of the route you could use replace:

var url = '@Url.Action("Action", "Controller", new { id = "_id_" })'
    .replace('_id_', rowid);

yet another possibility if you are going to send an AJAX request is to pass it as part of the POST body:

$.ajax({
    url: '@Url.Action("Action", "Controller")',
    type: 'POST',
    data: { id: rowid },
    success: function(result) {

    }
});

or as a query string parameter if you are using GET:

$.ajax({
    url: '@Url.Action("Action", "Controller")',
    type: 'GET',
    data: { id: rowid },
    success: function(result) {

    }
});

All those suppose that your controller action takes an id parameter of course:

public ActionResult Action(string id)
{
    ...
}

So as you can see many ways to achieve the same goal.

like image 94
Darin Dimitrov Avatar answered Nov 20 '22 02:11

Darin Dimitrov