如何解决使用视图模型类插入数据
模型类::
public class MappedModels
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MappedId { get; set; }
public int MappedType { get; set; }
public decimal MappedAmount { get; set; }
[ForeignKey("ProjectId")]
public ProjectModels Project { get; set; }
public int ProjectId { get; set; }
}
查看模型类::
public class MappedViewModels
{
public int MappedType { get; set; }
public decimal MappedAmount { get; set; }
public int ProjectId { get; set; }
public string ProjectName { get; set; }
// these two fields only in MappedViewModels for calculation purpose
public decimal ProjectAllocatedAmount { get; set; }
public decimal RemainingAmount { get; set; }
}
我已经使用MappedViewModels为Create.cshtml
创建了MappedModels
页面。现在,当我尝试提交表单时,出现错误::
The model item passed into the dictionary is of type 'myapp.Models.MappedModels',but this dictionary requires a model item of type 'myapp.ViewModels.MappedViewModels'.
我的创建控制器方法::
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MappedId,MappedType,MappedAmount,ProjectId")] MappedModels mappedModels)
{
if (ModelState.IsValid)
{
db.Mappeds.Add(mappedModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mappedModels);
}
如果我将方法更改为public ActionResult Create( MappedViewModels mappedModels)
,则在db.Mappeds.Add(mappedModels)
中出现错误
我必须使用MappedViewModels
中public ActionResult Create(int? ProjectId)
的字段。
此外,我的MappedViewModels
不包含属性MappedId
,如果我将其保留在(MappedViewModels)中,那么MappedId
怎么可以自动递增。>
那么如何使用MappedViewModels
到MappedModels
插入数据?
根据解决方案的建议,我尝试了::
public ActionResult Create([Bind(Include = "MappedType,ProjectId")] MappedViewModels model)
{
if (ModelState.IsValid)
{
var dbMappedModel = new MappedModels
{
MappedType = model.MappedType,MappedAmount = model.MappedAmount,ProjectId = model.ProjectId
}
db.Mappeds.Add(dbMappedModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mappedModels);
}
但是出现错误Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
。这是由于存在多个必填字段的Project类引起的。请帮忙!!!
解决方法
如下更新您的操作逻辑
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MappedType,MappedAmount,ProjectId")] MappedViewModels model)
{
if (ModelState.IsValid)
{
// when you add to the context,create a new MappedModels object
// You need not to worry about the MappedId,it will be auto incremented
var dbMappedModel = new MappedModels
{
MappedType = model.MappedType,MappedAmount = = model.MappedAmount,Project = new ProjectModels { ... }
}
db.Mappeds.Add(dbMappedModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mappedModels);
}
[Bind(Include = "MappedType,ProjectId")]
的用途是什么,我认为这不是必需的。我没用过。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。