Suresh
Suresh

Reputation: 61

Pass JavaScript variable to C# method in MVC

I'm trying to do the following in MVC: I have been trying to call a C# Method ReplaceSpecialCharactersInURL from JavaScript as follows

var SuppName= obj.data('suppliername');
var NewSupp= '@Common.ReplaceSpecialCharactersInURL(SuppName)';

But it throws me an error as follows :

The name 'SuppName' does not exist in the current context

On the other hand it runs ok when I pass the name directly as this

var NewSupp= '@Common.ReplaceSpecialCharactersInURL("NewName")';

What I can make out is I cant pass JavaScript variable to c# Method

Let me know if such a thing is possible, and if so, then how.

Upvotes: 2

Views: 2122

Answers (2)

Meryovi
Meryovi

Reputation: 6231

This is not possible in the way you're trying to do it because Razor is processed on the server side and JavaScript is processed on the client side.

One option you have is to ask the server to call Common.ReplaceSpecialCharactersInURL using an Ajax Request, like this:

Server:

public ActionResult ReplaceCharacters(string url) {
    string result = Common.ReplaceSpecialCharactersInURL(url);
    return Json(new { result });
}

Client:

<script type="text/javascript">
    var SuppName= obj.data('suppliername');

    // Using jQuery Ajax here.
    $.post('@Url.Action("ReplaceCharacters")', { url: SuppName },
        function (data) {
            var newUrl = data.result;
            // newUrl here is the result of Common.ReplaceSpecialCharactersInURL
        }
    );
</script>

Another option would be to create a JavaScript version of your server-side function (ReplaceSpecialCharactersInURL), but in some cases that could be really hard or even impossible.


Extra:

I don't know what your ReplaceSpecialCharactersInURL does, but you should check the encodeURIComponent JavaScript function just in case it helps you with this particular issue.

Upvotes: 1

Oleksandr Kobylianskyi
Oleksandr Kobylianskyi

Reputation: 3380

It's impossible, because Razor view engine knows nothing about your Javascript.

Upvotes: 1

Related Questions