Skip to main content
 首页 » 编程设计

jquery之将对象从 javascript 发送到 MVC 中的操作方法

2026年07月24日14zengkefu

我正在尝试将对象从 Razor View 发送到操作方法

我的看法

    <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> 

这是我的 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" }); 
        } 

它在 HomeController.cs 中的位置

当我检查响应时,我发现

[HttpException]:路径“/HomeController/saveexpense”的 Controller 未找到或未实现 IController。

请您参考如下方法:

为 Url.Action 指定 Controller 名称时helper 你只需要指定 Controller 的名称,不带单词 Controller,类似于:

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

假设您的其余代码正常,应该可以工作。