1

I have a variable in JavaScript and I want to use it as an index reference in my C# code. How do I convert the JavaScript variable into something C# can use? So far this is what I have..

@{
var selectedStockLocation = @Html.Raw(Json.Decode(document.getElementById("cbLocation " + id).value));

var currentLocation = Model.StockLocationBinData[selectedStockLocation];
}
4
  • 2
    See stackoverflow.com/questions/9516293/… Commented Mar 1, 2012 at 14:26
  • 1
    Where is the javascript? Where is the javascript variable? Commented Mar 1, 2012 at 14:26
  • could you post some more code to see how you want to communicate between View and your controller. @AndreLoker: I think that post is about how to handle it in webforms. Commented Mar 1, 2012 at 14:31
  • @PraveenLearnsEveryday right, but the issue is the same - he needs to post the data to the server. Commented Mar 1, 2012 at 14:38

3 Answers 3

0

You will have to post the value back with either a full POST or an AJAX call.

Sign up to request clarification or add additional context in comments.

Comments

0

You are mixing server and client code there.

You need to use (one of many) methods to post client data back to the controller.

Use jquery to write to a hidden variable in the form is one route, see this answer: Passing a jQuery value to MVC 3 Razor view html helper

Comments

0

JavaScript runs well after the server-side code has rendered and completed; you cannot use it while rendering the view.. You can, however, store the value in a hidden field, put this hidden field in a form, and process it during a post operation. Or, send it to the server via an AJAX callback.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.