例如: 觀有兩個形式:Form 1和Form
Form1的具有兩個部分。
第一部分: 有兩個文本框,一個創建按鈕和一個保存按鈕。
第二部分: 還有一個。
所以,當我們填寫兩個文本框並按下Create按鈕,如果沒有通過驗證,那麼就會顯示錯誤信息。 如果通過驗證,則將值插入到form2並將值插入到form2中。
[HttpPost]操作Create有一個參數List models。
當我們按下保存按鈕時,會將form2的值傳遞給控制器映射到List模型。
型號
public class HomeModel
{
[Required]
public string Name { get; set; }
[Required]
public string Number { get; set; }
}
控制器:
[HttpPost]
public ActionResult Create(List<HomeModel> models)
{
// TODO: Add insert logic here
}
查看:不管
@model MvcApplication1.Models.HomeModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "form1" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>HomeModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Number)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Number)
@Html.ValidationMessageFor(model => model.Number)
</div>
<p>
<input type="submit" value="Create" id="btnCreate" />
<input type="button" value="Save" id="btnSave" />
</p>
</fieldset>
<table id="tb"></table>
}
<div id="FormInfo" style="display: none;">
<form action="/Home/Create" id="form2" method="post"></form>
</div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function() {
$("#form1").submit(function() {
var ErrorLength = $(".field-validation-error").length;
if (ErrorLength <= 0) {
var nameValue = $("#Name").val();
var numberValue = $("#Number").val();
InsertToForm2(nameValue, numberValue);
InsertToTable(nameValue, numberValue);
}
return false;
});
$("#btnSave").click(function() {
$("#form2").submit();
});
});
function InsertToForm2(nameValue, numberValue) {
var inputCount = $("#form2 input").length/2;
var combineHTML = "<input type='text' name='models[" + inputCount + "].Name' value='" + nameValue + "' /> ";
combineHTML += "<input type='text' name='models[" + inputCount + "].Number' value='" + numberValue + "'/> ";
$("#form2").append(combineHTML);
}
function InsertToTable(nameValue, numberValue) {
var combineHTML = "<tr><td>" + nameValue + "</td><td>" + numberValue + "</td></tr>";
$("#tb").append(combineHTML);
}
</script>
}
Example Download
服務器端驗證應該工作。不過,客戶端驗證需要適當的屬性。你將不得不自己添加。但服務器端驗證沒有任何訪問權限,所以我不知道爲什麼你有問題。你如何綁定你的對象? –
我對服務器端驗證沒有任何問題 – joshb
從您的問題中不清楚。你聽起來像驗證沒有工作。是的,您必須手動添加驗證屬性(如果在客戶端進行)。 –