我建议你采取一种不同的,更好的方法,因为现在我看到你正在将C#,JavaScript和HTML混合到同一页面中,导致所谓的h可怕的标签汤。
所以改进1号:使用编辑器模板而不是那些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
当然是当前控制器的名称。如果您想在多个控制器之间重复使用,也可以将它放在~/Views/Shared/EditorTemplates
中。而且由于编辑器模板是强类型化的视图模型,您可以使用强类型帮助程序(如Html.TextBoxFor
),以便您不必手动硬编码文本框的名称和值,并想知道为什么模型联编程序无法正常工作。
改进号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;
});
});
感谢Frederic,Omkar进来之前,但我确实标记了:) – 2010-12-19 09:00:29