简体   繁体   English

MVC使用Controller中的TryUpdateModel形式检查表单中的模型值

[英]MVC Check model values in form using TryUpdateModel in Controller

I am currently following a tutorial on MVC 5, and I am stuck on how to perform validation checks on fields entered by the User without binding my fields in the Edit Method. 我当前正在关注有关MVC 5的教程,并且我坚持不对用户输入的字段执行验证检查,而不会在“编辑方法”中绑定我的字段。

I have a Edit page already in place, but this binds all fields at the start - the tutorial which I'm following makes it clear that I should not do this. 我已经有一个“编辑”页面,但是从一开始它就绑定了所有字段-我遵循的教程清楚地表明我不应该这样做。

My Original code is the following. 我的原始代码如下。 Since I bind all of my fields at the start, I can perform checks by using vans. 由于我一开始就绑定了所有字段,因此可以使用货车进行检查。 fieldname as shown below with 'if (vans.AssetID == 20)' 字段名称如下所示,带有“ if(vans.AssetID == 20)”

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "AssetID,Batch_Number,Customer_Account_Holder,Dealer_ID, ")] Vans__ vans)
    {
        if (vans.AssetID == 20) //Example - check if data entered for AssetID is 20
        {
          //do something
        }
        if (ModelState.IsValid)
        {
            db.Entry(vans__).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(vans__);
    }

In the tutorial that I'm following, I'm instructed not to bind everything at the start, but instead use code like the following: 在本教程中,我被指示不要在一开始就绑定所有内容,而应使用如下代码:

    public ActionResult EditPost(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        //In here vans is the original values and not from the form.
        Vans__ vans = db.Vans__.Find(id);

       //Here how can I check if AssetID is a certain number returned from the form?

        if (TryUpdateModel(vans, "", new string[] { "AssetID" }))
        {
            try
            {
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
    }

I understand the white-listing with the TryUpdateModel will be much easier and safer, I am just struggling to get to grips with how I get access to the data returned to the controller from the form. 我知道,使用TryUpdateModel列入白名单将更加容易和安全,我只是在努力了解如何访问从表单返回给控制器的数据。

How can I access the model in order for me to add my own validation Checks? 我如何访问模型以添加自己的验证检查?

All help is appreciated, thanks. 感谢所有帮助,谢谢。

This is not an answer. 这不是答案。

The Microsoft tutorial is here (Disclaimer I work with James and asked him to learn by posting the question). Microsoft教程在这里 (免责声明,我与James一起工作,并要求他通过发布问题来学习)。

And write up from it below relating to why we should not be using the original BIND method which James has linked. 并在下面写下有关为什么我们不应该使用James链接的原始BIND方法的信息。

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
  if (id == null)
  {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  }
  var studentToUpdate = db.Students.Find(id);
  if (TryUpdateModel(studentToUpdate, "",
   new string[] { "LastName", "FirstMidName", "EnrollmentDate" }))
  {
    try
    {
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    catch (DataException /* dex */)
    {
        //Log the error (uncomment dex variable name and add a line here to write a log.
        ModelState.AddModelError("", "Unable to save changes. Try again, and      if the problem persists, see your system administrator.");
    }
  }
  return View(studentToUpdate);
}

These changes implement a security best practice to prevent overposting, The scaffolder generated a Bind attribute and added the entity created by the model binder to the entity set with a Modified flag. 这些更改实现了安全最佳实践,以防止发布过多信息。脚手架生成了Bind属性,并将由模型绑定程序创建的实体添加到带有Modified标志的实体集。 That code is no longer recommended because the Bind attribute clears out any pre-existing data in fields not listed in the Include parameter. 不再建议使用该代码,因为Bind属性会清除Include参数中未列出的字段中的所有现有数据。 In the future, the MVC controller scaffolder will be updated so that it doesn't generate Bind attributes for Edit methods. 将来,将更新MVC控制器脚手架,以便它不会为Edit方法生成Bind属性。

The new code reads the existing entity and calls TryUpdateModel to update fields from user input in the posted form data. 新代码读取现有实体,并调用TryUpdateModel来更新发布的表单数据中用户输入的字段。 The Entity Framework's automatic change tracking sets the Modified flag on the entity. 实体框架的自动更改跟踪在实体上设置了Modified标志。 When the SaveChanges method is called, the Modified flag causes the Entity Framework to create SQL statements to update the database row. 调用SaveChanges方法时,Modified标志使Entity Framework创建SQL语句来更新数据库行。 Concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn't change. 并发冲突将被忽略,并且数据库行的所有列都将更新,包括用户未更改的列。 (A later tutorial shows how to handle concurrency conflicts, and if you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified.) (后面的教程显示了如何处理并发冲突,如果只希望更新数据库中的各个字段,可以将实体设置为“未更改”,并将各个字段设置为“已修改”。)

As a best practice to prevent overposting, the fields that you want to be updateable by the Edit page are whitelisted in the TryUpdateModel parameters. 作为防止过度发布的最佳实践,TryUpdateModel参数中将要由“编辑”页面更新的字段列入白名单。 Currently there are no extra fields that you're protecting, but listing the fields that you want the model binder to bind ensures that if you add fields to the data model in the future, they're automatically protected until you explicitly add them here. 当前没有您要保护的额外字段,但是列出希望模型绑定程序绑定的字段可确保如果将来在数据模型中添加字段,则这些字段将被自动保护,直到您在此处明确添加它们为止。

As a result of these changes, the method signature of the HttpPost Edit method is the same as the HttpGet edit method; 这些更改的结果是,HttpPost Edit方法的方法签名与HttpGet编辑方法相同。 therefore you've renamed the method EditPost. 因此,您已将方法重命名为EditPost。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用TryUpdateModel时的asp.net核心MVC控制器单元测试 - asp.net core mvc controller unit testing when using TryUpdateModel 使用TryUpdateModel绑定时,MVC ValidationSummary忽略模型级验证错误 - MVC ValidationSummary ignores model level validation errors when bound using TryUpdateModel ASP.NET 4.5 TryUpdateModel不使用Master-Page在WebForm中选择Form值 - ASP.NET 4.5 TryUpdateModel not picking Form values in WebForm using Master-Page MVC自定义模型绑定器使用默认绑定器表示某些表单值 - MVC custom model binder using the default binder for certain form values 将字符串模型传递回控制器(MVC表单) - Pass string model back to controller (MVC Form) 动态填充多个复选框并将已检查的值存储到MVC 4中表单中的一个模型字段中 - Dynamically populate multiple check-boxes and store checked values to one model field in form in mvc 4 如何将表单值传递给 .NET MVC 中的 Controller - How to pass Form Values to the Controller in .NET MVC 模型绑定Webform TryUpdateModel不起作用 - model binding webform TryUpdateModel not Working 表单POST之后,MVC模型向控制器返回null - MVC Model returns null to controller after Form POST 控制器中带有 FormCollection 模型的 ASP.NET CORE MVC 发布表单 - ASP.NET CORE MVC post form with FormCollection Model in controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM