How to fill a property (type Object) from a form

Asked

Viewed 46 times

1

I have the following code

@model ModelTransaction

<div class="form-group">
    <label for="name">Conta:</label>
    <select asp-for="Account"  class="form-control">
        @{
            foreach (ModelAccount account in (List<ModelAccount>)ViewBag.AccountList)
            {
                <option value="@account">@account.Name</option>
            }
        }
    </select>
</div>

This form aims to fill the Account property of the Modeltransaction object. However, this property has a Modelaccount type, that is, another object by the Asp-for tag. However, the way the above code is constructed, the request via post of this form does not fill the Account property, even having set this value in the form.

Would you have some way to fill in this object by this form?

Structure of the Modeltransaction:

namespace MyFinances.Models

{
    public class ModelTransaction
    {

        public int Id { get; set; }

        [Required(ErrorMessage = "Informe a data")]
        public string Date { get; set; }

        [Required(ErrorMessage = "Informe o valor")]
        public decimal Value { get; set; }

        [Required(ErrorMessage = "Informe a descrição")]
        public string Description { get; set; }

        public TransactionType Type { get; set; }
        public ModelUser User { get; set; }
        public ModelAccount Account { get; set; }
        public ModelAccountingPlan AccountingPlan { get; set; }

        public IHttpContextAccessor HttpContextAccessor { get; set; }

        public ModelTransaction()
        {

        }

        public ModelTransaction(IHttpContextAccessor httpContextAccessor)
        {
            this.HttpContextAccessor = httpContextAccessor;
        }
    }

Structure of the Modelaccount:

 namespace MyFinances.Models
{
    public class ModelAccount
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Informe o nome da conta")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Informe o saldo inicial da conta")]
        public decimal InitialBalance { get; set; }

        public ModelUser User { get; set; }
        public IHttpContextAccessor HttpContextAccessor { get; set; }


        public ModelAccount()
        {

        }

        public ModelAccount(IHttpContextAccessor httpContextAccessor)
        {
            this.HttpContextAccessor = httpContextAccessor;
        }
    }
  • 1

    You say in the question that makes a post form, but in the excerpt that posted in the question does not have the <form>, is complete? It would also be interesting to post the controller. I don’t know if your Modeltransaction is your entity BD, but if you will send this field in the post would not be interesting to have a Viewmodel that will have the List<Modelaccount>?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.