net core mvc 数据绑定 《2》

mvc core 模型绑定 控制绑定名称

》》》Bind 属性可以用来指定 模型应该 绑定的前缀

csharp 复制代码
public class MyController : Controller
{
    [HttpPost]
    public ActionResult Create([Bind(Prefix = "MyModel")] Ilist<MyModel> model)
    {
        // 模型绑定将尝试从请求的表单数据中绑定以"MyModel"为前缀的字段到model参数
        if (ModelState.IsValid)
        {
            // 执行相关操作,例如保存到数据库
            return RedirectToAction("Index");
        }
 
        return View(model);
    }
}

在这个例子中,[Bind(Prefix = "MyModel")]指定了模型应该绑定的前缀为"MyModel"。这意味着控制器操作Create在接收到HTTP POST请求时,会尝试从请求的表单数据中绑定以"MyModel"为前缀的字段到MyModel类型的参数。

cshtml 复制代码
 <form  method="post" action =''My/Action''>
  <input name="MyModel" id="xx" type="text" />
  <input name="MyModel" id="xxxx" type="text" />
  <input name="MyModel" id="xxxxx" type="text" />
 </form

另外,Bind属性也可以用来指定不应该绑定哪些属性:

csharp 复制代码
public class MyController : Controller
{
    [HttpPost]
    public ActionResult Edit([Bind(Exclude = "Salary")] Employee model)
    {
        // 模型绑定将尝试绑定除"Salary"以外的所有字段
        if (ModelState.IsValid)
        {
            // 执行更新操作
            return RedirectToAction("Index");
        }
 
        return View(model);
    }
}

在这个例子中,[Bind(Exclude = "Salary")]指定了在模型绑定时,"Salary"属性将不会被绑定。这通常用于安全考虑,防止用户修改敏感信息。

相关推荐
Cyan_RA96 小时前
SpringMVC REST 详解
java·spring·mvc·springmvc·restful·jquery·jsp
budingxiaomoli3 天前
Spring Web MVC 知识总结
spring·mvc
虾米Life4 天前
MVC与MVVM 架构
架构·mvc·mvvm
笛卡尔的心跳6 天前
Spring MVC 注解
java·spring·mvc
小松加哲7 天前
Spring MVC 核心原理全解析
java·spring·mvc
那个失眠的夜7 天前
RESTful 语法规范 核心注解详解
java·spring·mvc·mybatis
羌俊恩7 天前
Centos环境django项目部署过程
django·flask·centos·mvc·mtv·web项目框架
Foreer黑爷9 天前
Spring MVC原理与源码:从请求到响应的全流程解析
java·spring·mvc
曹牧10 天前
Spring MVC中使用HttpServletRequest和HttpServletResponse
java·spring·mvc
曹牧10 天前
Spring MVC配置文件
java·spring·mvc