我在Html.BeginCollectionItem块中使用@ Html.DropDownList时遇到问题。当我创建一个新记录时,我选择的值在HttpPost Action中正确返回。
但是当我尝试编辑现有记录时,视图没有显示DropDownList中当前选定的值。
“编辑”视图呈现部分_EditorForm视图,_EditorForm视图如下所示。
...
@foreach (ContactPhone item in Model.phones)
{
Html.RenderPartial("_PhoneEditorRow", item);
}
...
_PhoneEditorRow如下
@model CRM.Models.ContactPhone
@using CRM.Helpers;
@{
Layout = null;
}
<tr class="editor-table-phones-row">
@using (Html.BeginCollectionItem("phones"))
{
<td valign="top">
@Html.DropDownListFor(model => model.phoneTypeId, new SelectList(Model.phoneTypes, "id", "name"), "--SELECT--")
@Html.ValidationMessageFor(model => model.phoneTypeId)
</td>
<td valign="top">
@Html.EditorFor(model => model.phoneNumber)
@Html.ValidationMessageFor(model => model.phoneNumber)
</td>
<td>
<a href="#" class="delete-table-row">Eliminar</a>
</td>
}
</tr>
这是ContactPhone类
using System.Collections.Generic;
namespace CRM.Models
{
public class ContactPhone
{
public long? id { get; set; }
public PhoneType phoneType { get; set; }
public byte? phoneTypeId
{
get { return this.phoneType.id; }
set { this.phoneType.id = value; }
}
public string phoneNumber { get; set; }
public List<PhoneType> phoneTypes { get; set; }
public ContactPhone()
{
this.phoneType= new PhoneType();
this.phoneTypes = new List<PhoneType>();
}
}
}
和控制器
...
[Authorize]
public ViewResult Edit(
int id)
{
Contact model = new Contact();
try
{
model = DataProvider.GetContactById(id);
model.parameters = DataProvider.GetContactParameters();
this.LoadContactSelectLists(ref model);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
}
return View(model);
}
...
private void LoadContactSelectLists(
ref Contact model)
{
if (model.phones.Count > 0)
{
List<PhoneType> phoneTypes = DataProvider.GetAllPhoneTypes();
for (int i = 0; i < model.phones.Count; i++)
model.phones[i].phoneTypes = phoneTypes;
}
}
...