簡體   English   中英

Model 綁定在 Asp.net 核心 3.0 中不起作用

[英]Model bind doesn't work in Asp.net Core 3.0

在這篇文章https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.0 之后

[Bind] attribute
Can be applied to a class or a method parameter. Specifies which properties of a model should be included in model binding.

In the following example, only the specified properties of the Instructor model are bound when any handler or action method is called:

C#

Copy
[Bind("LastName,FirstMidName,HireDate")]
public class Instructor
In the following example, only the specified properties of the Instructor model are bound when the OnPost method is called:

C#

Copy
[HttpPost]
public IActionResult OnPost([Bind("LastName,FirstMidName,HireDate")] Instructor instructor)
The [Bind] attribute can be used to protect against overposting in create scenarios. It doesn't work well in edit scenarios because excluded properties are set to null or a default value instead of being left unchanged.

我有一個 model 定義為

public class Family
{
    public int ID { get; set; }
    public string Name { get; set; }

    public string Address { get; set; }
}

當我在 Web Api 控制器中使用它時,我預計輸入 faimly model 只有名稱屬性,但忽略地址屬性(空或空)。 PostMan Json 機身:

 {
"Name": "Faimly1",
"Address":"Address1"
 }

    [HttpPost]
    public async Task<ActionResult<Family>> PostFamily([FromBody][Bind("Name")] Family family)
    {
        Console.WriteLine(family.Name); // Expect the string "Family1".
        Console.WriteLine(family.Address); // Should be empty even I have passed a string value.
    }

當我使用 Postman 測試操作時,我仍然得到地址值。 我應該怎么辦? 我在 asp.net 核心 3.0 和 asp.net 核心 2.1 中都對此進行了測試,並得到了相同的結果。

或者這個綁定只適用於標簽助手?

您可以嘗試在 model class 中使用JsonIgnoreAttribute而不是 BindAttribute:

public class Family
{
    public int ID { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public string Address { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM