Mych
Mych

Reputation: 2553

Why am I getting variable not declared

I have the following in my partial view...

@Model.ServerDetails
<div>
..... various markup
</div>
<script type="text/javascript">
    var bs = '@Model.BackupServer';
    if (bs == null) {
        bs = "";
    }
    var bssn = bs + '|' + '@Model.ServerName';

    $(document).ready( function() {
        if (bs != "") {
          $getJSON('@UrlContent("~/Details/OtherBackedUpServers?bsn=" + bssn)', function(returnedServers) {
             ..... removed for brevity...
          }
        }
    });

Unfortunately bssn in the $getJSON() paramater is showing an error: 'bssn' is not declared. It may be inaccessible due to its protection level.

Can someone explain why and how I can correct it?

Thanks

Upvotes: 0

Views: 60

Answers (2)

OlafW
OlafW

Reputation: 700

Or write:

$getJSON('@UrlContent("OtherBackedUpServers", "Details")?bsn=' + bssn, function(returnedServers) {
             ..... removed for brevity...
          }

CORRECTION

$getJSON('@Url.Action("OtherBackedUpServers", "Details")?bsn=' + bssn, function(returnedServers) {
             ..... removed for brevity...
          }

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.

As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.

var url = '@Url.Action("OtherBackedUpServers", "Details", new { bsn= -1})';
url = url .replace('-1', bssn);
$.getJSON(url );

Or, Better pass the variable as payload

$.getJSON('@Url.Action("OtherBackedUpServers", "Details")', { bsn : -1});

Upvotes: 1

Related Questions