2

I have a javascript variable, output. I have a model variable (which is a List<String> dates). How can I add output to List<string> dates? In c# i would do something like so:

dates.Add(output);

But @Model.dates.Add(output); throws an error, because while in the @ it does not recognize javascript variables. How can I escape the @ to reference a javascript variable and then finish the statement?

3
  • 2
    Its not possible. Because the the javascript code is executed in the local browser and the c# code is executed on the server. You need to pass the varable to your controller and write it there into the List. Why do you need it adhoc in you list? Commented Jul 27, 2015 at 15:47
  • Well, I need it in my list eventually (I can put it in my list in the controller if I have to, I was just hoping I could do it client-side for simplicity on the server, seeing as I am already doing some formatting of my data on the client side. Commented Jul 27, 2015 at 15:52
  • As carl bussema told, you could send it vis jquery and ajax to your controller. But i suggest that you create the whole list, if possible, client side and then send the whole list once to your controller. Commented Jul 27, 2015 at 15:55

1 Answer 1

2

The short answer is: you can't. Javascript runs at the client; Razor runs on the server.

The longer answer is: if you use something like jQuery to send the data via AJAX, or even a form with hidden input fields, you could work with the data on the server and then reload the view with a new model, or redirect to a different view, as needed.

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

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.