4

【ASP.NET Core】模型绑定:重命名绑定字段 - 东邪独孤

 1 year ago
source link: https://www.cnblogs.com/tcjiaan/p/16413296.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【ASP.NET Core】模型绑定:重命名绑定字段

前面在写模型绑定相关的水文时,老周遗漏了一篇,特地补一下。

在 99.996 % 的情况下,咱们是不推荐自定义 Binder 的,毕竟那样做会增加开发工作量。其实内置的各种 Binder 基本能对付了。比较多见的情况应该是给字段另起一个名字。

举个示例,假设有下面这样一个类,它表示你家里的某台主机的配置。

    public class PC
    {
        public string? CPU { get; set; }
        public int MemorySize { get; set; }
        public string? BIOS { get; set; }
    }

然后,某控制器中有个 PostOne 方法,此方法接收 form 元素提交的数据,并绑定到 pc 参数。

        [Route("send")]
        public IActionResult PostOne(PC pc)
        {
            string s = $"CPU型号:{pc.CPU}\n内存大小:{pc.MemorySize}\nBIOS:{pc.BIOS}";
            s = "你的烂机:\n\n" + s;
            return Content(s);
        }

默认情况下,用于绑定的 form 内元素的 name 会与类的属性名字相同。

  <input name="CPU" type="text" />
  <input name="MemorySize" type="number" />
  ……

很多时候我们是想换个名字,比如改为 name="_cpu",name="_memsize"。这样一来,字段的名字就与类的属性名不匹配,需要在类定义上明确一下。

    public class PC
    {
        [ModelBinder(Name = "_cpu")]
        public string? CPU { get; set; }
        [ModelBinder(Name = "_memsize")]
        public int MemorySize { get; set; }
        [ModelBinder(Name = "_bios")]
        public string? BIOS { get; set; }
    }

ModelBinder 特性的 Name 属性就是用来给属性的绑定字段另起一个名字。

这时候,HTML 要改为:

<p>聊一下你的爱机</p>

<form method="post" action="/test/send">
    <table>
        <tr>
            <td>CPU:</td>
            <td><input name="_cpu" type="text"/></td>
        </tr>
        <tr>
            <td>内存大小:</td>
            <td><input name="_memsize" type="number"/></td>
        </tr>
        <tr>
            <td>BIOS:</td>
            <td><input name="_bios" type="text"/></td>
        </tr>
    </table>
    <button type="submit">提交</button>
</form>

 看看效果如何?

367389-20220626180623658-730296014.png

 367389-20220626180715022-1011044809.png

但是,有一点要注意,如果你使用了 form tag helper,那么,这个自己命名的字段名会有冲突。比如

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model TestApp.PC  //这个是模型类

<p>聊一下你的爱机</p>

<form method="post" asp-controller="BB" asp-action="PostOne">
    <table>
        <tr>
            <td>CPU:</td>
            <td><input asp-for="CPU"/></td>
        </tr>
        <tr>
            <td>内存大小:</td>
            <td><input asp-for="MemorySize"/></td>
        </tr>
        <tr>
            <td>BIOS:</td>
            <td><input asp-for="BIOS"/></td>
        </tr>
    </table>
    <button type="submit">提交</button>
</form>

要是用这种方法的话,那么在控制器类中无法读取到属性的值。目前老周还没找到解决方案,如果你答案,请告诉老周一声,也给大伙伴们做参考。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK