MVC 6 绑定属性消失了? [英] MVC 6 Bind Attribute disappears?

查看:24
本文介绍了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.

假设你有一个像

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,在可编辑字段中显示 FirstNameLastName.因此,即使用户通过某种方式发布了更新的用户名,我们也不应该更新该字段值.

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 绑定属性消失了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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