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

相关推荐
optimistic_chen1 天前
【Java EE进阶 --- SpringBoot】Spring IoC
spring boot·后端·spring·java-ee·mvc·loc
wuk9981 天前
在Spring MVC中使用查询字符串与参数
java·spring·mvc
原来是好奇心3 天前
深入剖析Spring Boot中Spring MVC的请求处理流程
spring boot·spring·mvc
xkroy3 天前
创建Spring MVC和注解
学习·spring·mvc
期待のcode3 天前
SpringMVC的请求接收与结果响应
java·后端·spring·mvc
Pure03193 天前
Spring MVC BOOT 中体现的设计模式
spring·设计模式·mvc
The Sheep 20233 天前
.NetCore MVC
mvc·.netcore
YDS8293 天前
SpringMVC —— Spring集成web环境和SpringMVC快速入门
java·spring·mvc·springmvc
xkroy4 天前
Sping Web MVC入门
mvc
他们都不看好你,偏偏你最不争气4 天前
【iOS】MVC架构
前端·ios·mvc·objective-c·面向对象