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"属性将不会被绑定。这通常用于安全考虑,防止用户修改敏感信息。

相关推荐
想要一只奶牛猫1 天前
Spring Web MVC(三)
前端·spring·mvc
独断万古他化2 天前
【Spring Web MVC 入门实战】实战三部曲由易到难:加法计算器 + 用户登录 + 留言板全流程实现
java·后端·spring·mvc
csdnZCjava2 天前
Spring MVC工作原理 及注解说明
java·后端·spring·mvc
想要一只奶牛猫2 天前
Spring Web MVC(四)
前端·spring·mvc
qq_398898933 天前
【备忘】ASP.Net MVC无缝对接SQL Server数据库设置步骤
数据库·asp.net·mvc
苏婳6664 天前
Java---SSH(MVC)面试题
java·ssh·mvc
AI题库4 天前
1.3 ABP MVC开发环境搭建指南:从零开始快速上手
asp.net·mvc·.net·.netcore
独断万古他化6 天前
【Spring Web MVC 入门续篇】请求处理之 Cookie 与 Session 获取实战
后端·spring·java-ee·mvc
阿拉斯攀登7 天前
设计模式:Spring MVC 中命令模式的核心映射与设计逻辑
spring·设计模式·mvc·命令模式
七夜zippoe7 天前
Spring MVC请求处理流程源码分析与DispatcherServlet核心逻辑
java·spring·mvc·过滤器·拦截器