MVC 6 绑定属性消失?

编程入门 行业动态 更新时间:2024-10-21 18:59:02
本文介绍了MVC 6 绑定属性消失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请原谅我的菜鸟问题,但我注意到绑定属性在 MVC 6 的控制器模板中不再显示为默认值.

Pardon me for my noob question but I notice that the bind attribute does not appears as default in controller template anymore for MVC 6.

我知道该属性仍然存在,但我们还需要使用它们吗?我听说它们可以用来防止过度发布攻击.他们是否将其删除是因为 MVC 6 可以在不使用它们的情况下找出防止这种情况的方法?还是有更安全的方法来防止这种情况发生?

I know I that the attribute is still present but do we still need to use them? I heard they can be use to prevent over-posting attack. Do they remove it because MVC 6 can figure out the way to prevent this without using them? Or is there a more secure way to prevent that?

推荐答案

防止过度发布的最好方法是获取实体,只更新需要更新的属性并保存.

The best way to prevent overposting is to get the entity, update only the properties needed to update and save it.

假设你有一个类似的视图模型

Assuming you have a view model like

public class CustomerViewModel { public int Id {set;get;} public String UserName {set;get;} public String FirstName {set;get;} public String LastName {set;get;} }

并假设有一个名为 Update 的视图,它以只读/仅显示形式显示 UserName,在可编辑字段中显示 FirstName 和 LastName.因此,即使用户通过某种方式发布了更新的 UserName,我们也不应该更新该字段值.

And assume there is a view called Update which shows UserName in readonly/display only form and FirstName and LastName in editable fields. So even if user posts an updated UserName via some means, we should not be updating that field value.

[HttpPost] public ActionResult Update(CustomerViewModel model) { var customer = yourDbContext.Customers.FirstOrDefault(s=>s.Id==model.Id); if(customer!=null) { // Updating only fields which are supposed to be updated from the view. customer.FirstName = model.FirstName; customer.LastName = model.LastName; yourDbContext.Entry(customer).State = EntityState.Modified; yourDbContext.SaveChanges(); return RedirectToAction("UpdatedSuccessfully"); } return View("NotFound"); }

更多推荐

MVC 6 绑定属性消失?

本文发布于:2023-11-08 13:59:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   属性   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!