I know there are already a few posts on this subject but I cannot seem to figure out an answer to my specific issue. I am confused as to why I cannot pass a variable into the controller but I can pass in a hardcoded value…
This works…
<script type="text/javascript">
$().ready(function () {
$("#MessageTypes").change(function () {
//I know this is a horrible way to do it but for some reason I couldnt pass the sMessageType directly in
var sMessageType = $("#MessageTypes").val();
if (sMessageType == "Professional Voicefile") {
$.get('@Url.Action("GenerateMessageDesc", new { MessageType = "Professional Voicefile" } )', function (data) {
$('#MessageDesc').replaceWith(data);
});
}
else if (sMessageType == "Dynamic Field") {
$.get('@Url.Action("GenerateMessageDesc", new { MessageType = "Dynamic Field" } )', function (data) {
$('#MessageDesc').replaceWith(data);
});
}
else {
//default to prof
$.get('@Url.Action("GenerateMessageDesc", new { MessageType = "Professional Voicefile" } )', function (data) {
$('#MessageDesc').replaceWith(data);
});
}
});
});
…But this does not. Why?
<script type="text/javascript">
$().ready(function () {
$("#MessageTypes").change(function () {
var sMessageType = $("#MessageTypes").val();
$.get('@Url.Action("GenerateMessageDesc", new { MessageType = sMessageType } )', function (data) {
$('#MessageDesc').replaceWith(data);
});
}
});
});
It says “The name ‘sMessageType’ does not exist in the current context”.
I think maybe I should be using some kind of ajax call instead to call the controller and update the view instead of how I am doing it — however, why does scenario 1 work but not scenario 2?
sMessageTypeis a javascript variable that lives on the client that you are trying to use inside a server side helper. That obviously is impossible because javascript runs on the client and server side script on the server.Here’s the correct way to achieve that:
this will pass the MessageType as query string parameter, so your target controller action might look like this: