1

我正在尝试使用 linq to 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" });
    }

查询:

$(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
)
4

1 回答 1

0

在控制器处编辑:

  ...
 if (HttpContext.Request.IsAjaxRequest())
    {
     return Json(new { message = "Hours Saved"  }, JsonRequestBehavior.AllowGet);
    }
  ...
于 2012-12-20T06:42:12.483 回答