-1
public PersonViewModel()
{
Children = new List<ChildViewModel>();
}
[Required(ErrorMessage = "Required!")]
public string FName { get; set; }
[Required(ErrorMessage = "Required!")]
public string LName { get; set; }
public List<ChildViewModel> Children{ get; set; }
}
public class ChildViewModel
{
[Required(ErrorMessage = "Required!")]
public string FName { get; set; }
[Required(ErrorMessage = "Required!")]
public int Age { get; set; }
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(PersonViewModel person)
{
if (!ModelState.IsValid)
{
return View(person);
}
return View();
}
public ActionResult AddChildBox(PersonViewModel person,int id)
{
ViewBag.Counter = id;
return PartialView("View");
}
}
我通過Ajax調用局部視圖創建視圖顯示兒童對兒童
<script type="text/javascript">
var num = 0;
$("#AddChildBtn").click(function() {
$.ajax({
type: 'GET',
url: '@Url.Content("~/Home/AddChildBox/")',
data: {
Id: num
},
dataType: 'html',
success: function (result) {
$('#Fields').append(result);
num = num + 1;
}
});
});
</script>
領域與此代碼
@if (Model != null)
{
for (int i = 0; Model.Child.Count>i;i++)
{
@Html.Action("AddChildBox", "Home", new { id = i })
}
}
和我的部分查看
@model WebApplication4.Models.PersonViewModel
@{
int i = ViewBag.Counter;
}
<div class="form-group">
@Html.LabelFor(model => model.Child[i].FName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Child[i].FName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Child[i].FName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Child[i].Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Child[i].Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Child[i].Age, "", new { @class = "text-danger" })
</div>
</div>
這可行,但是當從AddChildBox
中刪除人員操作方法參數時,部分視圖字段的驗證消息不起作用。 我不會在我的動作中使用它,那麼爲什麼我需要它? 我很困惑,誰可以向我解釋在這段代碼中發生了什麼?
當您提交時,您的ChildViewModel列表是否爲空?你的部分不知道你的原始模型,所以它正在創建一個新模型。你可以讓你的孩子成爲一個ChildViewModel的數組,然後在你的部分,只要做''。當你提交時,你的模型現在會有一系列的孩子。 –