I'm not too sure if I understand your question correctly. I never use EditorFor
, I just add the fields directly from the view model. It gives me more control. From what I can gather it seems like you want to edit class A
and have class B
in a drop down list?
This is how I will define class A
and class B
given the names of your properties, please excuse if I am mistaken. class A is class User
and class B is class Organization
. You need to give your properties better descriptions so that people can read them better.
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; }
}
You need to have a view model to represent your data on your view.
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
}
And this is how your view will look like.
@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>
}
This is how I do it. You can modify the code to fit in with your scenario.
I hope this helps.