Rakesh
Rakesh

Reputation: 92

access the variable in my javascript from controller

In my CSHTML I have some JavaScript which contains a string variable. How do I access this variable from my controller?

Upvotes: 0

Views: 936

Answers (3)

Massimo Zerbini
Massimo Zerbini

Reputation: 3191

You can use a hidden input field in your form valorized with the value of your string variable. When you post the form you can read the value as usual.

Upvotes: 1

Rafay
Rafay

Reputation: 31043

[HttpPost]
public ActionResult someAction(string id)
{
return Content("got it");
}

in script

$(function(){

var someid='12';
$.post('/Controller/someAction',{id:someid},function(data){
//this call back is executed upon successfull POST
console.log(data); // got it"

});
});

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

When you invoke the controller you could pass it as parameter. For example if you are invoking the controller action using AJAX:

$.post('/someaction', { someValue: someVariable }, function() {
    ...
});

Upvotes: 4

Related Questions