您好我有一个下拉列表,我希望将该列表中的值保存到数据库中这是我在控制器类中的操作方法
public ActionResult NewRequest(Bookinfo bookinfo)
{
using (var db = new Database1Entities1())
{
return View(db.Bookinfoes.ToList());
}
}
这是我的下拉列表视图
@model IEnumerable<MvcApplication.Models.Bookinfo>
@{
ViewBag.Title = "NewRequest";
}
<h2>NewRequest</h2>
<table>
<tr>
<td>
@Html.DropDownList("Bookname", Model.Select(m => new SelectListItem() { Text = m.Bookname, Value = m.Bookname }).ToList())
</td>
@*<td>
@Html.DropDownList("Authorname", Model.Select(m => new SelectListItem() { Text = m.Authorname, Value = m.Authorname }).ToList())
</td>
<td>
@Html.DropDownList("Publishername", Model.Select(m => new SelectListItem() { Text = m.Publishername, Value = m.Publishername }).ToList())
</td>
<td> </td>*@
</tr>
<tr> <td> <input type = submit value="Reserve" name="Reserve"></td></tr>
</table>
我想将值保存在一个名为issued的表中,表示该书是以当前日期发出的,如果该书已经存在,我想显示一些消息
这是我的数据库结构或更确切的Issued表结构
CREATE TABLE [dbo].[Issued] (
[BookId] INT NOT NULL,
[date] DATETIME NOT NULL,
[IssueID] INT IDENTITY (1, 1) NOT NULL,
PRIMARY KEY CLUSTERED ([BookId] ASC),
FOREIGN KEY ([BookId]) REFERENCES [dbo].[Bookinfo] ([Id])
};
答案 0 :(得分:0)
这样做的一种方法是让数据库捕获这种错误。
通过添加如下语句使您的字段Issued.BookId
唯一:
CREATE TABLE [dbo].[Issued] (
[BookId] INT NOT NULL,
[date] DATETIME NOT NULL,
[IssueID] INT IDENTITY (1, 1) NOT NULL,
PRIMARY KEY CLUSTERED ([BookId] ASC),
FOREIGN KEY ([BookId]) REFERENCES [dbo].[Bookinfo] ([Id])
CONSTRAINT AK_IssueId UNIQUE(IssueId)
};
然后,当您尝试向同一Issued
的{{1}}添加新记录时,将会抛出BookId
。捕获此异常并显示错误消息。