18

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?
    }

2 Answers 2

53

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I wonder why the first answer isn't working. The ajax answers works well.
No event is triggered even in firebug. The URL doesn't change.
What is the generated URL in your HTML? Right click in your browser and view source. Also what are you doing with the url variable next if you are not sending an AJAX request? How do you expect the browser to navigate away from the current page? What code you have written? I cannot read your mind.
I tired using $.get(url, function (result)){ } . I found my mistake, it was silly that i didn't create resultholder. Now it works. Thank you.
i really wonder why any of the options above will work? @Url.Action("Action", "Controller") is razor syntax. JavasScript (i.e onRowSelected event handler) will get executed in the browser which does know anything about @Url.Action. Am i missing something?
0

The method by Darin will work fine and perfectly.

I would suggest one more way for Razor view to use model value using @Html.actionlink in jsp

var URLvalue='@Html.ActionLink("UserString", "action", new { routeValueName1 = "__value1__", routeValueName2="__value2__" }, htmlAttributes: new { @class = "btn btn-default", @role = "button" })'
     .replace('__value1__', Model.somevalue).replace('__value2__',  Model.somevalue);

you can use URLvalue where ever you want to in jsp or jquery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.