我正在尝试使用C#/ LINQ(CodeBehind)和JavaScript(在.aspx中)开发代码,该代码将测试是否已经存在添加到数据库的值。我的目标是避免系统错误消息,暂停处理,并显示一个警告,指示尝试添加的值是重复值。似乎我正在使用的代码首先触发JavaScript(即在我的LINQ查询检查重复之前)。因此,我无法准确读取LINQ查询。 tbxChannel
包含要添加到数据库的值。任何帮助将非常感谢。我正在使用VS 2010,我的代码如下:
LINQ / C#:
var getChannel = (from c in db.Channel
where c.Channel1 == tbxChannel.Text
select new { c.Channel1 }).ToList();
if (getChannel.Count > 0)
{
string tbxDupChannel = getChannel[0].Channel1;
return;
}
JavaScript的:
if (document.getElementById("<% = tbxDupChannel.ClientID %>").value.length > 0)
{
var dupChannel = document.getElementById("<% = tbxDupChannel.ClientID %>").value;
window.alert("Update Aborted... " + dupChannel +
" is already on the database and cannot be added a second time.");
return;
}
答案 0 :(得分:0)
尝试这样的事情
LINQ / C#:
// Make DupChannel a public property
public string DupChannel { get; set; }
public void Page_Load(object sender, EventArgs e)
{
var getChannel = (from c in db.Channel
where c.Channel1 == tbxChannel.Text
select new { c.Channel1 }).ToList();
if (getChannel.Count > 0)
{
DupChannel = getChannel[0].Channel1;
return;
}
JavaScript的:
var dupChannel = '<%= DupChannel %>';
if (dupChannel.length > 0)
{
window.alert("Update Aborted... " + dupChannel +
" is already on the database and cannot be added a second time.");
return;
}
答案 1 :(得分:0)
我采用了不同的方法,并通过将JavaScript Alert嵌入我的CodeBehind来解决我的问题:
if (getChannel.Count > 0)
{
string dupChannel = getChannel[0].Channel1;
Response.Write(@"<script language='javascript'>alert('Update Aborted... \n \nChannel " + dupChannel + " is already on the database and cannot be added a second time.');</script>");
tbxChannel.Text = "";
tbxChannel.Focus();
return;
}