我不太确定我是否正确理解了你的问题。我从不使用EditorFor
,我只是直接从视图模型中添加字段。它给了我更多的控制权。据我所知,您似乎想编辑class A
并class B
在下拉列表中?
这就是我将如何定义class A
并class B
给出您的属性的名称,如果我弄错了,请原谅。class A is class User
和class B is class Organization
。您需要为您的属性提供更好的描述,以便人们可以更好地阅读它们。
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int OrganizationId { get; set; }
}
public class Organization
{
public int OrganizationId { get; set; }
public string OrganizationName { get; set; }
public string OrganizationDescription { get; set; }
}
您需要有一个视图模型来在视图上表示您的数据。
public class EditUserViewModel
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int OrganizationId { get; set; }
public IEnumerable<Organization> Organizations { get; set; }
}
public ActionResult Edit(int id)
{
// Get the user by id
User user = userRepository.GetById(id);
// You can use a mapping tool here to map from domain model to view model.
// I did it differently for the sake of simplicity
EditAViewModel viewModel = new EditAViewModel
{
UserId = user.UserId,
FirstName = user.FirstName,
LastName = user.LastName,
OrganizationId = user.OrganizationId,
Organizations = organizationRepository.GetAll()
};
// Return the populated view model to the view
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(EditAViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Organizations = organizationRepository.GetAll();
return View(viewModel);
}
// If validation succeeds do what ever you have to do here, like edit in database
}
这就是您的视图的样子。
@model YourProject.ViewModels.Users.EditUserViewModel
@using (Html.BeginForm())
{
<table>
<tr>
<td class="edit-label">First Name:</td>
<td>
@Html.TextBoxFor(x => x.FirstName)
@Html.ValidationMessageFor(x => x.FirstName)
</td>
</tr>
<tr>
<td class="edit-label">Last Name:</td>
<td>
@Html.TextBoxFor(x => x.LastName)
@Html.ValidationMessageFor(x => x.LastName)
</td>
</tr>
<tr>
<td class="edit-label">Organization:</td>
<td>
@Html.DropDownListFor(
x => x.OrganizationId,
new SelectList(Model.Organizations, "OrganizationId", "OrganizationName", Model.OrganizationId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.OrganizationId)
</td>
</tr>
</table>
<button id="SaveButton" type="submit">Save</button>
}
我就是这样做的。您可以修改代码以适应您的场景。
我希望这有帮助。