0

How can I insert a JavaScript variable into razor? I'm incrementing counter by the amount of times the user clicks on insert-comment button, and then I have a JavaScript function that adds new input boxes for Comment. However, I'm having trouble properly inserting counter as the array index because I'm getting a "the name 'counter' does not exist in the current context" error.

Model:

public List<String> Comment {get; set;}

View:

var counter= 0;

jQuery(function($) {
    $('#insert-comment').on("click", function(e) {
        $(this).closest('tr').prev('tr').find('ul')
            .append(
                '<li>' +
                '@Html.EditorFor(model => model.Comment[counter], new { htmlAttributes = new { @class = "form-control col-xs-12" } })' +
                '</li>');
    });
    counter++;
});
1
  • 1
    You can't. Razor is processed on the server before any JS is run. After that, Razor is no longer running. Instead, you probably want to have a local copy of Comment that you manipulate. var comments = @Html.Raw(Json.Encode(model.Comment)); Commented Feb 10, 2016 at 17:33

2 Answers 2

0

You could copy your variable value in an html element using razor.

This element could be read in javascript.

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

Comments

0

I don't think you can as the html helper is rendered before any client scripting. I would just append the html for the editor like so.

'<li><input type="input" name="Comment[' + counter + ']" class = "form-control col-xs-12"></li>';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.