MVC,将数据从单个表单/视图保存到2个或更多相关模型
本文关键字:2个 模型 保存 视图 数据 单个 表单 MVC | 更新日期: 2023-09-27 17:52:17
我的模型:(i)交易
public class Transaction
{
[Key]
public int TransactionId { get; set; }
public DateTime OnWardDate { get; set; }
public DateTime ReturnDate { get; set; }
public virtual UserProfile User { get; set; }
}
(ii)对于用户
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
private UserDetails _details = new UserDetails();
public virtual UserDetails details
{
get { return _details; }
}
}
(ii) For UserDetails
public class UserDetails
{
[Key]
public int DetailsId { get; set; }
public string DLNum { get; set; }
}
My Controller for Create Transaction:
// GET: /Transaction/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Transaction/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Transaction transaction)
{
if (ModelState.IsValid)
{
db.Transactions.Add(transaction);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(transaction);
}
My View for Create transaction:
<div class="editor-label">
@Html.LabelFor(model => model.OnWardDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.OnWardDate)
@Html.ValidationMessageFor(model => model.OnWardDate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.User.details.DLNum)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.User.details.DLNum)
@Html.ValidationMessageFor(model => model.User.details.DLNum)
</div>
当我提交表单…模型。OnWardDate正在被保存,但model.User.details.DLNum没有保存
关于ViewModel。这是唯一的选择吗?
在你的情况下,我认为这是因为你的setter是私有的UserDetails:
public virtual UserDetails details
{
get { return _details; }
}
如果你正在创建基于这些模型的表,因此不能修改它们,我确实建议创建一个视图模型,使用它,然后相应地创建/更新数据库条目
- 主要问题是实体框架需要getter和setter的POCO属性,你的类UserDetails只有一个getter定义的细节属性。
你的模型可以是:
public class Transaction
{
[Key]
public int TransactionId { get; set; }
public DateTime OnWardDate { get; set; }
public DateTime ReturnDate { get; set; }
public virtual UserProfile User { get; set; }
}
public class UserProfile
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual UserDetails Details { get; set; }
}
public class UserDetails
{
[Key]
public int DetailsId { get; set; }
public string DLNum { get; set; }
}
2。我建议使用在控制器中实例化模型并将其传递给视图的模式,如下所示:
public ActionResult Create()
{
var transaction = new Transaction
{
User = new UserProfile
{
Details = new UserDetails()
}
};
return View(transaction);
}
这确保你的模型被正确构造,并允许你在渲染视图之前初始化任何属性。你通常可以避开这种捷径,但我认为最好是明确说明。