我试图创建一个页面来编辑“人物”,但是我在如何编辑List对象方面遇到了麻烦(并且通过编辑,我的意思是如何动态添加一封电子邮件到列表)。在线研究和stackoverflow研究使我进入EditorTemplates,然后使用ajax动态添加项目。但是,我错过了某个地方的联系。要么为新电子邮件创建未绑定的空文本框,要么获取空引用错误。
型号:
[DynamoDBTable("people")]
public class Person
{
[DynamoDBHashKey]
[DynamoDBProperty(AttributeName = "name")]
public string Name{ get; set; }
[DynamoDBRangeKey]
[DynamoDBProperty(AttributeName = "id")]
public string ID { get; set; }
[DynamoDBProperty(AttributeName = "emails")]
public List<string> Emails{ get; set; }
public Person()
{
}
}
查看:
<div id="emails" class="row">
<div class="form-group col-xs-6 col-sm-6">
@Html.LabelFor(x => x.Emails)
@Html.EditorFor(x => Model.Emails, new { @class = "form-control"})
</div>
<button id="addEmail">Add</button>
</div>
<script type="text/javascript">
$("#addEmail").on('click', function (event) {
event.preventDefault();
$.ajax({
async: false,
url: '/controller/newEmail'
}).success(function (partialView) {
$('#emails').append(partialView);
});
});
</script>
EditorTemplate - 人:
@model Models.Person
@for (int i = 0; i < Model.Emails.Count(); i++)
{
@Html.EditorFor(x => Model.Emails)
}
EditorTemplate - String:
@model string
@Html.TextBoxFor(model => Model)
控制器:
public ActionResult newEmail()
{
var emails = new Person().Emails;
return PartialView("~/Views/Shared/EditorTemplates/string.cshtml", emails);
}
答案 0 :(得分:0)
您的Person.Emails
对象为空且尚未初始化
public ActionResult newEmail()
{
var emails = new Person().Emails;
return PartialView("~/Views/Shared/EditorTemplates/string.cshtml", emails);
}
将其更改为:
public ActionResult newEmail()
{
var emails = new Person().Emails = new List<string>();
return PartialView("~/Views/Shared/EditorTemplates/string.cshtml", emails);
}