我有一个存储过程如下:
ALTER PROCEDURE [dbo].[Addworkshop]
@title varchar(100),
@time varchar(10),
@date date,
@mandatory int,
@sid int
AS
BEGIN
SET NOCOUNT ON;
insert into Workshop(title, date, time, mandatory, sid)
values(@title, @date, @time, @mandatory, @sid)
declare @wid int
set @wid = scope_identity()
return @wid
END
我从ASP.NET MVC5 C#中的action方法调用它:
public JsonResult addWorkshop(Workshop workshop)
{
TLCWREntities context = new TLCWREntities();
var wid = db.Addworkshop(workshop.title, workshop.time, workshop.date, workshop.mandatory, workshop.sid);
return Json(wid);
}
使用JSON ajax调用此方法:
$.ajax({
type: 'POST',
url: '@Url.Action("addWorkshop")', // we are calling json method
dataType: 'json',
data: $.toDictionary(wsData),
success: function (wid) {
console.log("success add workshop wid: "+wid);
},
error: function (ex) {
console.log("err add workshop");
}
});
数据已成功插入到表中,当我在SQL Server Management Studio中执行存储过程时,它返回正确的新插入行ID。但是,当我使用JSON ajax和action方法调用存储过程时,它总是返回-1。
我正在使用Visual Studio 2013 MVC5 C#和SQL Server Studio 2008
答案 0 :(得分:3)
在@ user2946329的帮助下以及Google上的一些搜索,我设法得到答案。 我改变了我的存储过程:
insert into Workshop(title, date, time, mandatory, sid)
values(@title, @date, @time, @mandatory, @sid)
declare @wid int
set @wid = SCOPE_IDENTITY()
select @wid AS wid
我使用select
语句而不是return
答案 1 :(得分:0)
在我创建存储过程以便在插入后返回ID的情况下,它会在我看来,我强烈推荐以下内容:
public JsonResult addWorkshop(Workshop workshop)
{
TLCWREntities context = new TLCWREntities();
db.Workshops.Add(workshop);
db.SaveChanges(); //when this executes, `workshop` gets its `id` field populated
return Json(workshop.sid);
}
答案 2 :(得分:0)
试试这个
int workShopId = 0;
using (TLCWREntities context = new TLCWREntities ())
{
context.Workshop.InsertOnSubmit(workshop);
context.SubmitChanges();
workShopId = workshop.ID;//ID is column from you workshop table
}