Mvc模型绑定,保存时缺少一个字段 [英] Mvc model binding, missing one field when save

查看:101
本文介绍了Mvc模型绑定,保存时缺少一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在MVC中使用模型绑定。

Say I use model binding in MVC.

public ActionResult Edit(MyModel model)
{
    db.SaveChanges();
    return View(model);
}



当我们通过模型时,我们会错过模型中的一个字段。

如果我们将其保存到db?



我尝试了什么:



不确定但是我猜测


When we pass the model, we miss one field in the model.
What will happen if we save it to db?

What I have tried:

Not sure but I guess

It depends if the field that you forgot to set is mandatory or not.

推荐答案

基于代码你已发布,它根本不会做任何事情。没有代码从发布的数据更新数据库,因此数据库不会更新。



您需要从检索相应的实体开始数据库:

Based on the code you've posted, it won't do anything at all. There's no code to update the database from the posted data, so the database won't be updated.

You'll need to start by retrieving the corresponding entity from the database:
var entity = db.YourSet.Find(model.PrimaryKey);
if (entity == null) return RedirectToAction("Index");



然后,您需要复制发布数据中的值。您可以手动执行此操作:


You'll then need to copy the values from the posted data. You can either do that manually:

entity.Prop1 = model.Prop1;
entity.Prop2 = model.Prop2;
...



或者您可以使用 TryUpdateModel [ ^ ]方法。但是您需要明确说明可以更新哪些属性,以防止恶意用户覆盖不应更改的内容:


Or you can use the TryUpdateModel[^] method. But you'll want to explicitly state which properties can be updated, to prevent a malicious user from overwriting things that shouldn't be changed:

TryUpdateModel(entity, new[] { "Prop1", "Prop2", ... });



完成后,然后可以保存更改:


Once you've done that, then you can save the changes:

db.SaveChanges();
return View(model);



如果您不从发布中复制属性数据,或不包括在包含的属性列表中,那么数据库值将不会被更改。



如果您复制/包含该属性,但是用户未输入值,则清除数据库值。如果属性是必需的,则在尝试保存时会出现验证错误。否则,将覆盖数据库中的值。


If you don't copy a property from the posted data, or don't include it in the list of included properties, then the database value will not be changed.

If you copy / include the property, but the user didn't enter a value, then the database value will be cleared. If the property is required, you'll get a validation error when you try to save. Otherwise, the value in the database will be overwritten.


这篇关于Mvc模型绑定,保存时缺少一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆