0

This will probably be a rather simple question.

How do I pass:

var ident = $(this).attr("id");

to

content.load("@Html.Raw(Url.Action("Action", "Controller", new {id=ident}))");

I've tried:

... new {id="+ident+"}))"); but it doesn't work.

Solution

For my specific problem, the best solution I found was the following:

var ident = $(this).attr("id");
var route = "@Html.Raw(Url.Action("Action", "Controller"))";
var url = addParameterToURL(route, ident);
content.load(url);

With the method:

function addParameterToURL(url, param) {
    _url = url;
    _url += (_url.split('/')[1] ? '/' : '/') + param;
    return _url;
}
Community
  • 1
  • 1
Leigh Cooper
  • 168
  • 1
  • 8

1 Answers1

0

Please feel the difference here between server-side code and client-side code. This:

var ident = $(this).attr("id");

is javascript, it is executed on the client's page. While this:

"@Html.Raw(Url.Action("Action", "Controller"))"

Is a server-side code, that is executed on the server way before page goes to the client. You simply cannot mix the two with the things like concatenation.

The easiest way for you would be to store the result of server-side execution into some variable, and then add a param to it. Store it like this:

var url = "@Html.Raw(Url.Action("Action", "Controller"))";

And then, while in JS, add a parameter to it. Use this function for example (just make sure to make an url as a param, rather than using current location).

Community
  • 1
  • 1
Andrei
  • 53,252
  • 9
  • 82
  • 104
  • I need to pass an id to the action method in the controller to get the correct result. If I can specify string literals `Action` and `Controller` is there really no way to pass in a param? Is `"@Html.Raw(Url.Action("Action", "Controller", new {id=ident}))"` not basically a string? Or is there a better way that I should be calling the method of the controller so that I can render a partial view to a Bootstrap Modal? – Leigh Cooper Nov 19 '15 at 11:36
  • The approach I suggested will pass id to the controller. It will just giver you the URL like this: `/Controller/Action?id=123`, which is exactly what you need to pass 123 as an id to Action. – Andrei Nov 19 '15 at 11:38
  • @LeighCooper, no it is not, since Razor recognizes it and renders it into a proper URL string while rendering the VIew – Andrei Nov 19 '15 at 11:39
  • Thanks I'll have a go of it. – Leigh Cooper Nov 19 '15 at 11:39