刚刚接触 JQuery 和 Asp.net MVC 2,想知道如何将变量从循环传递到 JavaScript 函数。
所以我有:
<% int i = 0; %>
<% foreach (var item in Model) { %>
<tr>
<td>
<input type="button" id="btnSubmit" value="Save" onclick="javascript:updatePerson(i);" />
<input type="text" id='<%= "persons[" + i + "].Name" %>' name='<%= "persons[" + i + "].Name" %>' value='<%=item.Name %>' />
</td>
</tr>
<% i++; %>
<% } %>
显然
onclick="javascript:updatePerson(i);"
错误。
如何将变量 i 传递到 updatePerson 函数中?
京东
最佳答案
我建议您采取不同的、更好的方法,因为现在我看到您将 C#、javascript 和 HTML 混合到同一个页面中,这导致了所谓的可怕的标签汤。
所以改进一:使用编辑器模板而不是 foreach 循环。在您的主视图中,不要简单地写下您在问题中发布的内容:
<%= Html.EditorForModel() %>
然后定义一个编辑器模板,该模板将自动为模型集合中的每个元素调用(~/Views/Home/EditorTemplates/Person.ascx
):
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<YourApp.Models.Person>" %>
<tr>
<td>
<% using (Html.BeginForm("Save", "Persons",
new { id = Model.Id }, FormMethod.Post,
new { @class = "saveform" })) { %>
<%= Html.TextBoxFor(x => x.Name) %>
<input type="submit" value="Save" />
<% } %>
</td>
</tr>
请注意,部分的名称与其强类型化的类型名称相同 (Person.ascx
)。另请注意位置:~/Views/Home/EditorTemplates
,其中 Home
当然是当前 Controller 的名称。如果您想在多个 Controller 之间重用它,也可以将其放置在 ~/Views/Shared/EditorTemplates
中。而且由于编辑器模板是强类型化到 View 模型的,因此您可以使用强类型帮助程序,例如 Html.TextBoxFor
,这样您就不必手动对文本框的名称和值进行硬编码,并且想知道为什么会这样模型绑定(bind)器无法正常工作。
改进 2:在单独的 javascript 文件中使用 jquery 逐步增强标记:
$(function() {
$('.saveform').submit(function() {
// When the form is submitted
// For example you could call the associated action using AJAX:
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('successfully saved');
}
});
return false;
});
});
关于jquery - 如何在jquery for循环变量中传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482205/