我建議你採取一種不同的,更好的方法,因爲現在我看到你正在將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