Sending an object from javascript to an action method in MVC

I am trying to send an object from a razor to an action method

my opinion

<section> <script type="text/javascript"> function saveExpense() { var expenseobject = { date:$('.txtDate').val() , type:$('.ExpenseType').val() , cost: $('.cost').val(), extra:$('.extra').val() }; $.ajax({ // url: baseUri+'HomeController/saveexpense', url: '@Url.Action("saveexpense", "HomeController")', type: 'POST', contentType: 'application/json', data: JSON.stringify({ obj: expenseobject }), success: function (result) { } }); } </script> <section id="form"> <table width="600"> <tr> <td>Select Date:</td> <td> <input class="txtDate" type="date" size="20"></td> </tr> <tr> <td>Select Expense Type:</td> <td> <select class="ExpenseType"> <optgroup label="Room"> <option>Room Fare</option> </optgroup> <optgroup label="Mess"> <option>Monthly Mess</option> </optgroup> <optgroup label="Others"> <option>Bus Fare</option> <option>Tapari</option> <option>Mobile Recharge</option> <option>Auto</option> </optgroup> </select></td> </tr> <tr> <td>Enter Cost:</td> <td> <input class="cost" type="text" size="45" /></td> </tr> <tr> <td>Extra Details:</td> <td> <input class="extra" type="text" size="45" /></td> </tr> <tr> <td>&nbsp;</td> <td> <button onClick="saveExpense();" >Submit</button></td> </tr> </table> </section> </section> 

And this is my controller

  public ActionResult saveexpense(Expense obj) { obj.ExpenseId = Guid.NewGuid(); Debug.Print(obj.cost.ToString()); if (ModelState.IsValid) { context.expenses.Add(obj); context.SaveChanges(); int total = context.expenses.Sum(x => x.cost); return Json(new { spent = total, status = "Saved" }); } return Json(new { status = "Error" }); } 

Where does he go to HomeController.cs

when i check the answer i find

[HttpException]: The controller for the path '/ HomeController / saveexpense' was not found or does not implement IController.

+4
source share
1 answer

When specifying the controller name for Url.Action, the assistant needs to specify only the name of the controller without the word Controller , similar to this:

 url: '@Url.Action("saveexpense", "Home")', 

Suppose the rest of your code is in order, which should work.

+2
source

All Articles