Asp.Net Core Model binding, how to get empty field to bind as a blank string?

后端 未结 2 677
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 16:45

If a form like the one below is submitted and MyField is left blank on the form, then by default Asp.Net Core model binding will place null into the correspondi

2条回答
  •  悲哀的现实
    2021-01-12 17:11

    Have you tried making the property have a default value of empty string?

    public string MyField { get; set; } = string.Empty;
    

    an uglier solution to try is:

    private string myField  = string.Empty;
    public string MyField 
    {
        get { return myField ?? string.Empty; }
        set { myField = value; }
    }
    

    I think it should work

提交回复
热议问题