This question already has an answer here:
这个问题在这里已有答案:
- using javascript variable in MVC3 Razor view engine 2 answers
在MVC3中使用javascript变量Razor视图引擎2的答案
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.
如何在剃刀中插入JavaScript变量?我按照用户点击插入注释按钮的次数递增计数器,然后我有一个JavaScript函数,为Comment添加新的输入框。但是,我无法正确插入计数器作为数组索引,因为我得到一个“名称'计数器'在当前上下文中不存在”错误。
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++;
});
2 个解决方案
#1
0
You could copy your variable value in an html element using razor.
您可以使用razor在html元素中复制变量值。
This element could be read in javascript.
这个元素可以在javascript中读取。
#2
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.
我不认为你可以在任何客户端脚本之前呈现html帮助器。我会像这样为编辑器添加html。
'<li><input type="input" name="Comment[' + counter + ']" class = "form-control col-xs-12"></li>';
#1
0
You could copy your variable value in an html element using razor.
您可以使用razor在html元素中复制变量值。
This element could be read in javascript.
这个元素可以在javascript中读取。
#2
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.
我不认为你可以在任何客户端脚本之前呈现html帮助器。我会像这样为编辑器添加html。
'<li><input type="input" name="Comment[' + counter + ']" class = "form-control col-xs-12"></li>';