ASP.Net MVC 前台数据绑定到后台TryUpdateModel方法

ASP.Net MVC TryUpdateModel方法

Binding属性

Model Binding 在使用上非常方便,Model在进行Binding动作时,不管Model有多少字段,只要窗体有字段都会自动进行Binding动作。但是正常情况下可能出于安全原因,不会把整个数据表的内容完全展示给用户端,设置黑白名单可以解决这个问题。

BindAttribute有两个主要属性

1.Exclude:设置不允许进行绑定的属性名称列表;
2.Include:设置允许进行绑定的属性名臣列表;

public ActionResult Create([Bind(Include = "ID,Name,Subject")] Student student)
{
    
    
    if (ModelState.IsValid)
    {
    
    
        db.Student.Add(student);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(student);
}

TryUpdateModel

Binding是获取数据,然后赋予Model的过程;Validation检查Model里的数据是否符合验证规则,这完全是不同的工作,但是Model Binding模糊了他们的区别。Model Binding是一种【隐式】的后台工作机制。如果想【显示】的调用Model Binding,可以在Action方法里调用TryUpdateModel方法。

TryUpdateModel的返回值

TryUpdateModel方法的源代码可知,方法最后返回bool类型值,该值为ModelState.IsValid,如下代码两种写法都可以。

public ActionResult Edit()
{
    
    
    UserInfo userInfo = new UserInfo();
    
    //写法1-清晰
    TryUpdateModel(userInfo);
    if (ModelState.IsValid)
    {
    
    

    }

    //写法2-简洁
    if(TryUpdateModel(userInfo))
    {
    
    

    }

    return View(userInfo);
}

TryUpdateModel的 includeProperties 和 excludeProperties

使用includeProperties或excludeProperties参数,等同于Bind属性的include与exclude属性。
1.采用includeProperties的重载:

// 参数:
//   model:要更新的模型实例。
//   includeProperties: 一个要更新的模型的属性列表。
protected internal bool TryUpdateModel<TModel>(TModel model, string[] includeProperties) where TModel : class;

2.采用includeProperties和excludeProperties的重载:

// 参数:
//   model:要更新的模型实例。
//   prefix:在值提供程序中查找值时要使用的前缀。
//   includeProperties:一个要更新的模型的属性列表。
//   excludeProperties: 要从该更新中显式排除的属性列表。即使 includeProperties 参数列表中列出了这些属性,也会将其排除。
protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class;

3.采用includeProperties和excludeProperties的实例:
在这里插入图片描述
数据表UserInfo字段与属性设置
在这里插入图片描述

@model WebApplication21.Models.UserInfo

<html>
<head>
    <script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
</head>
<body>
    <h2>This is an Edit Page</h2>
    <h4>UserInfo</h4>
    <hr/>

    <form id="formEdit" class="form-horizontal" method="post" action="/UserInfo/Edit">
        <div class="form-group">
            <label>Name</label>
            <input id="name" name="Name" type="text" placeholder="Please input user name" class="form-control" value="@Model.Name" readonly/>
        </div>

        <div class="form-group">
            <label>Age</label>
            <input id="age" name="Age" type="text" placeholder="Please input user age" class="form-control" value="@Model.Age" />
        </div>

        <div class="form-group">
            <label>Gender</label>
            <input id="gender" name="Gender" type="text" placeholder="Please input user gender" class="form-control" value="@Model.Gender" />
        </div>

        <div class="form-group">
            <label>Address</label>
            <input id="address" name="Address" type="text" placeholder="Please input user address" class="form-control" value="@Model.Address" />
        </div>

        <div class="form-group">
            <label>Phone</label>
            <input id="phone" name="Phone" type="text" placeholder="Please input user phone" class="form-control" value="@Model.Phone" />
        </div>

        <div class="form-group">
            <label>Role</label>
            <select id="role" name="Role" class="form-control">
                <option value="Admin" selected>Admin</option>
                <option value="Worker">Worker</option>         
            </select>
        </div>

        <div class="form-group">         
            <input id="submit" type="submit" Value="Edit" class="btn btn-success"/>
            <a class="btn btn-default" href="/UserInfo/Index">Go Back</a>
        </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication21.Models;

namespace WebApplication21.Controllers
{
    
    
    public class UserInfoController : Controller
    {
    
    
        // GET: UserInfo
        private readonly TestEntities db = new TestEntities();
        public ActionResult Index()
        {
    
    
            return View(db.UserInfo.OrderBy(o=>o.ID).ToList());
        }

        public ActionResult Edit(string Name)
        {
    
    
            if (Name == null)
            {
    
    
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }    

            if (ModelState.IsValid)
            {
    
    
                UserInfo userInfo = db.UserInfo.Find(Name);
                return View(userInfo);
            }
            else
            {
    
    
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
        }   

        [HttpPost]
        public ActionResult Edit(FormCollection formCollection)
        {
    
    
            UserInfo userInfo = new UserInfo();
            TryUpdateModel(userInfo, "", formCollection.AllKeys, new[] {
    
     "ID", "LastUpdateName" });
            
            if (ModelState.IsValid)
            {
    
    
                userInfo.LastUpdateTime = DateTime.Now.ToString();
                db.Entry<UserInfo>(userInfo).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            else
            {
    
    
                string error = null;
                foreach(var value in ModelState.Values)
                {
    
    
                    foreach (var item in value.Errors)
                    {
    
    
                        error += item.ErrorMessage;
                    }
                }
                return View(userInfo);
            }
        }

        protected override void Dispose(bool disposing)
        {
    
    
            if (disposing)
            {
    
    
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

注意事项:
1.FormCollection的用法,formCollection.AllKeys;
2.数据表所示,部分字段不允许为空,在写TryUpdateModel方法时,确认includeProperties或excludeProperties是否包含了不许为空的字段,否则EF可能会出错;
实例中正确写法:
TryUpdateModel(userInfo, “”, formCollection.AllKeys, new[] { “ID”, “LastUpdateName” });
实例中错误写法:
TryUpdateModel(userInfo, “”, formCollection.AllKeys, new[] { “LastUpdateName” });

Happy Ending…

猜你喜欢

转载自blog.csdn.net/ryancao530/article/details/111879653