我正在尝试使用linq到SQL和jquery在表中插入数据,但是它失败了,无法找到原因。
以下是我的工作方式:
控制器:
[HttpPost]
public ActionResult SaveHours(string descType, string wrkType, decimal hours)
{
DataContext db = new DataContext();
Project hrs = new Project ();
{
hrs.descType = descType;
hrs.wrkType = wrkType;
hrs.hours= (decimal)hours;
}
db.Project.InsertOnSubmit(hrs);
db.SubmitChanges();
return Json(new { message = "Hours Saved" });
}
JQuery的:
$(function(){
$("#SaveHours").click(function (e) {
e.preventDefault();
var link = '/Project/SaveHours';
$.ajax({
type: 'POST',
url: link,
data: { hours: $("#HoursWorked").val(),
descType: $("#Description").val(),
wrkType: $("#WorkType").val()
},
dataType: 'json',
success: function (result) {
alert(result.message);
},
error: function (result) {
alert("Failed");
}
});
});
查看:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<UI.Models.vwProject>>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div>
<table>
<tr>
<th>
Description
</th>
<td>
<input id="Description" type="text"/>
</td>
</tr>
<tr>
<th>
Work Type
</th>
<td>
<input id="WorkType" type="text"/>
</td>
</tr>
<tr>
<th>
Hours Worked
</th>
<td>
<input id="HoursWorked" type="text"/>
</td>
</tr>
<tr>
<td>
<button id="SaveHours" type="button" >Save</button>
</td>
</tr>
</table>
</div>
我在这里遗漏了什么吗? 非常感谢任何帮助。
编辑: 表脚本:
CREATE TABLE [Project]
(
ProjectKey INT IDENTITY(1,1) NOT NULL,
descType VARCHAR(100) NULL,
wrkType VARCHAR(10) NULL,
hours NUMERIC(5,2) NULL
)
答案 0 :(得分:0)
控制器编辑:
...
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new { message = "Hours Saved" }, JsonRequestBehavior.AllowGet);
}
...