【发布时间】:2011-10-18 05:49:55
【问题描述】:
我想我应该在页面顶部写下我的问题,因为后面有一堆垃圾代码。
我有一个包含内部视图模型列表的外部视图模型。当我在创建页面上单击保存并转到创建 POST 函数public ActionResult Create(DeviceTypeEntryViewModel model) 时,外部模型已填充,但其内部视图模型列表为空。我做错了什么?
视图模型是:
public class DeviceTypeEntryViewModel
{
public int ID { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public List<AttributeEntryViewModel> Attributes { get; set; }
}
public class AttributeEntryViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Private { get; set; }
}
创建包含设备条目视图的视图:
@model ICMDB.ViewModels.DeviceTypeEntryViewModel
@{
ViewBag.Title = "ICMD - Create Device Type";
}
<h2>Create Device Type</h2>
<div class="form-div">
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
Html.RenderPartial("_DeviceTypeEntryPartial", Model);
<input type="submit" value="Save" class="form-button"/>
}
@using (Html.BeginForm("Index", "DeviceType"))
{
<input type="submit" value="Cancel" class="form-button"/>
}
</div>
设备入口视图部分:
@model ICMDB.ViewModels.DeviceTypeEntryViewModel
<fieldset>
@Html.HiddenFor(model => model.ID)
<div> @Html.LabelFor(model => model.Type) </div>
<div>
@Html.EditorFor(model => model.Type)
@Html.ValidationMessageFor(model => model.Type)
</div>
<div> @Html.LabelFor(model => model.Description) </div>
<div>
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<table id="AttributesTable" class="editor-table">
<tr>
<th>Name</th>
<th>Description</th>
<th>Private</th>
</tr>
@Html.EditorFor(model => model.Attributes)
</table>
<input id="addAttributeButton" type="button" value="Add"
onclick="AddAttribute()" />
</fieldset>
AttributeEntryViewModel 的编辑器模板:
@model ICMDB.ViewModels.AttributeEntryViewModel
@Html.HiddenFor(model => model.ID)
<tr>
<td>
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</td>
<td>
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</td>
<td>
@Html.EditorFor(model => model.AttributePrivate)
</td>
</tr>
AJAX 调用添加属性行:
<script type="text/javascript">
function AddAttribute() {
// and send it as AJAX request
$.ajax({
url: '@Url.Action("AddAttribute")',
type: 'POST',
cache: false,
success: function (result) {
// when the AJAX succeeds add result to the table
$('#AttributesTable').append(result);
}
})
}
</script>
AJAX调用另一端的控制器函数用于添加:
[HttpPost]
public ActionResult AddAttribute()
{
var model = new AttributeEntryViewModel();
return PartialView("EditorTemplates/AttributeEntryViewModel", model);
}
【问题讨论】:
标签: .net asp.net-mvc ajax