Reputation: 13616
I have button and when It clicked process event have been called and parameter passed to the event.
Here the code:
<input type="button" value="Accessing Layers" onclick="process('AccessingLayers');" />
function process(actionName) {
$.ajax({
url: '@Url.Action(actionName)',
type: 'POST',
data: {
sessionID: parent.parent.mapFrame.sessionId,
mapName: parent.parent.mapFrame.mapName
},
success: function (result) {
alert('Successfully passed data to controller');
}
});
}
But in this row:
url: '@Url.Action(actionName)'
I get this error:
The name 'actionName' does not exist in the current context
Any idea why I get error above?
And how to fix it?
Upvotes: 0
Views: 1999
Reputation: 9013
<input type="button" value="Accessing Layers" id="btnAccessingLayers" />
and in scripts section
$(document).ready(function () {
$('#btnAccessingLayers').on('click', function(){
process('@Url.Action("AccessingLayers")');
}
});
function process(actionUrl) {
$.ajax({
url: actionUrl,
// existing code
});
}
Upvotes: 1
Reputation: 218722
Remember razor code executes on the server before the your client side code gets executed. So you cannot pass a javascript variable to a razor method like that.
If you still want to build the url using the Url.Action helper method and pass it to your process method, you should call the Url.Action
method with correct arguments(the action method,controller name etc..) and generate the url and pass the url( generated by razor) to your javascript method as a string parameter value
<input type="button" value="Accessing Layers"
onclick="process('@Url.Action("AccessingLayers")')" />
and your js code
function process(actionUrl) {
$.ajax({
url: actionUrl,
// existing code
});
}
Upvotes: 1
Reputation: 29
Everything typed between quotes is parsed as plain text, therefore no computation is performed on retrieving value of actionName.
You have to break your url like this:
url: '@Url.Action('+actionName+')'
so that actionName gets resolved as variable.
Upvotes: -1