0

Well im doing a application where i have a model like this

public class Saldo
{
    public Saldo()
    {
        Expenses = new List<Expese>();
        Incomes = new List<Income>();
    }

    public int SaldoId { get; set; }
    public List<Expense> Despesas { get; set; }
    public List<Income> Rendimentos { get; set; }
    public string ApplicationUserId { get; set; }
}

what i want to do is add a single expense to the list but it is not working, when i output on the console the count it is always null in the controller im doing this:

 public ActionResult Create([Bind(Include = "ExpenseId,TipoDespesaId,DespesaDescricao,DespesaValor,TipoPagamentoId,Data,Comentario")] Expense expense)
    {
        var userId = User.Identity.GetUserId();
        if (ModelState.IsValid)
        {

            var balance = db.Balance.Where(d => d.ApplicationUserId == userId).FirstOrDefault();


            expense.ApplicationUserId = userId;

            if (balance == null)
            {
                Balance s = new Balance();
                s.Expense.Add(expense);
                s.ApplicationUserId = userId;
                db.Balance.Add(s);             
            }
            else
            {
                Balance.Expense.Add(expense);
            }

            db.Expense.Add(expense);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

The expense comes from the form and is passed to the Action

I created a new instance of Balance it worked adding the ApplicationUserId but the expense on the list didnt work, can someone explain me why it happen?

Ps: Sorry for my bad english

2
  • What's the "db" variable? Do you ever tell it to save? Commented Mar 25, 2016 at 20:05
  • I edited the question and posted all the code, sorry should posted it previously Commented Mar 25, 2016 at 20:11

1 Answer 1

1

Perhaps it's just lost in the translation, but your model doesn't make sense. You have a list of Expense called "Despesas" but in the constructor you call it "Expenses" Whatever that list is called is what you need to add your expense object to. Instead of

s.Expense.Add(expense);

it would be

s.Despesas.Add(expense);
Sign up to request clarification or add additional context in comments.

1 Comment

just lost in the translation, the expense is never added dont know why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.