简体   繁体   中英

ASP.net core Web API post array as a property

I use an array to store tags of question, but when i POST data from Chrome i do not receive any data on TagId Array. Other Properties are OK and i receive them onlu TagId is null Here is my Code:

Question.cs

public partial class Question 
{

    [Key]
    public int Id { get; set; }

    ...

    [Display(Name = "Tags")]
    [NotMapped]
    public int[] TagId
    {
      get
      {
          Some Code Here
      }

      set
      {
        Tag = "";
        if(value==null)
          return;
        foreach (var i in value)
        {
          Tag = i + ",";
        }

        Tag = Tag.Trim(',');
      }
    }

    [ScaffoldColumn(false)]
    public string Tag { get; set; }
    ...
}

Here is chrome post with dummy data Chrome post Data and i receive null in asp.net Post Data: Visual Studio Trace on Data receive

here is my controller post code:

QuestionsController.cs

[Route("adminapi/[controller]")]
[ApiController]
public class QuestionsController : BaseRControllerWithFile<Question,QuestionAdminRepository>
{
...
  public override async Task<ActionResult<Question>> Post(Question entity)
  {
    return await base.Post(entity);
  }
...
}

Change the Question class to this :

public class Question
{
    private int[] tagId;

    private string tag;

    [Key]
    public int Id { get; set; }

    [Display(Name = "Tags")]
    [NotMapped]
    public int[] TagId
    {
        get => tagId;
        set
        {
            tagId = value;

            tag = "";
            if (value == null)
                return;
            foreach (var i in tagId)
            {
                tag += i + ",";
            }

            tag = tag.Trim(',');
        }
    }

    [ScaffoldColumn(false)]
    public string Tag => tag;
}

Or as @Paul said; you can use Join :

tag = value != null ? string.Join(',', tagId) : null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM