David Budiman
David Budiman

Reputation: 33

Simultaneously insert 2 rows of data into the same model item ASP.NET Core

Is possible to add data in same form, in same model item but different data like this?

See Kodeakun model item in the screenshot I attached. Sorry my English is bad.

My model class:

public class Transaksi
{
    [Key]
    public int Id { get; set; }
    public string Kodeakun { get; set; }
    public string Keterangan { get; set; }

    [DataType(DataType.Date)]
    public DateTime Tanggal { get; set; }

    [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
    public decimal Debit { get; set; }

    [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
    public decimal Kredit { get; set; }
}

My controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Kodeakun,Keterangan,Tanggal,Debit,Kredit")] Transaksi transaksi)
{
        if (ModelState.IsValid)
        {                               
            var debit = new Transaksi
            {
                Kodeakun = transaksi.Kodeakun,
                Keterangan = transaksi.Keterangan,
                Tanggal = transaksi.Tanggal,
                Debit = transaksi.Debit,
                Kredit = 0
            };

            var kredit = new Transaksi
            {
                Kodeakun = transaksi.Kodeakun,
                Keterangan = transaksi.Keterangan,
                Tanggal = transaksi.Tanggal,
                Debit = 0,
                Kredit = transaksi.Kredit
            };

            _context.Add(debit);
            _context.Add(kredit);

            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }
}

Here the screenshot:

From Here

To Here

And I ended like this:

My currently

Upvotes: 2

Views: 166

Answers (1)

habib
habib

Reputation: 2446

Yes, You can do this by making a ViewModel and adding two properties of Transaksi class in it.

public class TransactionVM
{
    public Transaksi First {get; set;}
    public Transaksi Second {get; set;}
}

Now in your Create view, you can bind TransactionVM model instead of Transaksi model. And now your create method signature should look like this.

public async Task<IActionResult> Create(TransactionVM transaction)

And you can get both entries by transaction.First and transaction.Second.

Upvotes: 2

Related Questions