我试图preserve /保护某些字段在一个视图模型 [英] I'm trying to Preserve/Protect certain fields in a View Model
本文介绍了我试图preserve /保护某些字段在一个视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现这里找到了解决办法,但一旦我代替我的用户类 EditUserViewModel级(具有比类的用户较少的领域之一),一旦我得到这个行
I'm trying to implement the solution found here, but once I replace my "Users" class with the "EditUserViewModel" class (the one that has less fields than the Users class) and once I get to this line
db.Entry(users).State = EntityState.Modified;
在此code
[HttpPost]
public ActionResult Edit(EditUserViewModel users)
{
if (ModelState.IsValid)
{
db.Entry(users).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(users);
}
我得到的错误
The entity type EditUserViewModel is not part of the model for the current context.
现在我猜这个错误,因为我的DbContext使用了类的用户,而不是EditUserViewModel类。我缺少的一个步骤或者是有没有什么办法解决这一问题?
Now I'm guessing this error is because my DBContext uses the Users class and not the EditUserViewModel class. Am I missing a step or is there any way to fix this?
推荐答案
您需要从MV中的数据合并到模型类。
You need to merge the data from your MV to your Model class.
if (ModelState.IsValid)
{
var existingUser = db.Users.Single(p => /* query to find your user */);
existingUser.From = user.From;
existingUser.CC = user.CC;
// etc.
db.SaveChanges();
return RedirectToAction("Index");
}
这篇关于我试图preserve /保护某些字段在一个视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文