C#C
C#3y ago
Ugly God

✅ How can I pass data from JS to a ViewModel?

Sorry in advance if the issue is JS related.

I'm trying to make a small MVC project - I'm having trouble trying pass an object from JS then to the Controller. I can pass the data normally when using a Model but I don't know how to do it when dealing with a ViewModel.
The Transactions Model would always return a NULL.

Any help is very much appreciated. Many Thanks!

JS Function:

function insert() {
    var formData = {
        Transactions: {
            Transactions_Id: $('#Transactions_Id').val(),
            Transactions_TransactionName: $('#Transactions_TransactionName').val(),
            Transactions_Description: $('#Transactions_Description').val()
        }
    }

    $.ajax({
        url: '/customer/dashboard/insert', type: 'post', data: JSON.stringify(formData), contentType: 'application/json',

...


Controller:
public IActionResult Insert(TransactionsVM transactionsVM)
  {
      if (ModelState.IsValid)
      {
          _unitOfWork.Transactions.Add(transactionsVM.Transactions);
          _unitOfWork.Save();
          return Json("Transaction Recorded");
      }
      return Json("Model Invalid, not saved");
  }


ViewModel:
    public class TransactionsVM
    {
        public Transactions Transactions { get; set; }
        [ValidateNever]
        public IEnumerable<SelectListItem> IncomeList { get; set; }
        [ValidateNever]
        public IEnumerable<SelectListItem> ExpenseList { get; set; }
    }
}
Was this page helpful?