我有三个模型一起创建一个视图模型,我希望能够在单击“编辑”时编辑该视图模型。我找不到一个直接的例子来说明它是如何工作的(在任何地方)。
我不确定我是否走在正确的道路上。我能够通过数据获得视图。在这一点上,我无法保存它。
任何帮助,将不胜感激。
谢谢!
楷模:
public class Person
{
[Key]
public int Id { get; set; }
[MaxLength(20)]
[Required(ErrorMessage = "First name is required.")]
public string FirstName { get; set; }
[MaxLength(20)]
[Required(ErrorMessage = "Last name is required.")]
public string LastName { get; set; }
[MaxLength(40)]
[Required(ErrorMessage = "Email is required.")]
public string Email { get; set; }
[MaxLength(20)]
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
public bool Active { get; set; }
}
public class ClientContact
{
[Key]
[ForeignKey("Person")]
public int ClientPersonId { get; set; }
public int ClientId { get; set; }
[MaxLength(40)]
public string Title { get; set; }
public Person Person { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
}
public class Client
{
[Key]
public int ClientId { get; set; }
public string Name { get; set; }
public bool Active {get;set;}
}
查看型号:
public class ClientContactViewModel
{
private SimplexDB db = new SimplexDB();
public ClientContactViewModel()
{
}
public ClientContactViewModel(int id)
{
ClientPersonId = id;
InitializeClientContact();
}
public int ClientPersonId { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = " Last Name")]
public string LastName { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Email Address")]
public string Email { get; set; }
[Display(Name = "Phone")]
public string Phone { get; set; }
[Display(Name = "Client Name")]
public int ClientId { get; set; }
public SelectList Clients
{
get
{
return new SelectList(db.Clients, "ClientId", "Name");
}
}
private void InitializeClientContact()
{
var contact = db.ClientPersons.Include("Person").Where(x => x.ClientPersonId == ClientPersonId).SingleOrDefault();
if (contact != null)
{
FirstName = contact.Person.FirstName;
LastName = contact.Person.LastName;
Title = contact.Title;
Email = contact.Person.Email;
Phone = contact.Person.Phone;
ClientId = contact.ClientId;
}
}
}
控制器:
public class ClientContactController : Controller
{
private database db = new database();
//
// GET: /ClientContact/Edit/5
public ActionResult Edit(int id)
{
return View(new ClientContactViewModel(id));
}
//
// POST: /ClientContact/Edit/5
[HttpPost]
public ActionResult Edit(ClientContactViewModel model)
{
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
}
我在 db.Entry(model).State...“实体类型 ClientContactViewModel 不是当前上下文模型的一部分。”