我有一个绑定到ClientEntitydatasource的详细信息视图。在DetailsView_ItemInserting中,我正在尝试检查用户是否已插入所有字段并根据该字段显示弹出窗口。
问题
我发现如果detailsview 绑定到数据源,则无法执行:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (e.Values["Name"] == null)
{
string script = "alert('Please Insert all the mandatory Fields');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true); //would not get execute.
}
}
为了做到这一点,我必须明确地将项目添加到相应的数据源,而且我还没有将它绑定到.aspx中的ClentEntityDatasource,如下所示:
protected void DetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
FileUpload FileUploadControl = DetailsView.FindControl("FileUpload1") as FileUpload;
if (FileUploadControl.HasFile && e.Values["Name"] != null)
{
string Name = e.Values["Name"].ToString();
try
{
string FileName = Path.GetFileName(FileUploadControl.FileName);
string MapPath = "~/Images/" + FileName;
FileUploadControl.SaveAs(Server.MapPath("~/Images/") + FileName);
byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(MapPath));
SqlConnection myConnection;
string myConnectionString = "Initial Catalog=42HNetDb;Data Source=localhost;Integrated Security=SSPI";
myConnection = new SqlConnection(myConnectionString);
string myInsertQuery = "INSERT INTO Client (Name,Logo) Values(@Name,@Logo )";
SqlCommand myCommand = new SqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myCommand.Parameters.Add("@Name", SqlDbType.NVarChar);
myCommand.Parameters["@Name"].Value = Name;
myCommand.Parameters.Add("@Logo", SqlDbType.Image);
myCommand.Parameters["@Logo"].Value = imgdata;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
string script = "alert('Please Insert all the mandatory Fields');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true); //gets executed properly
}
总之,我发现如果Detailsview绑定到某个数据源 ClientScript.RegisterClientScriptBlock 将无法执行。
我也尝试过使用 ScriptManager.RegisterStartupScript ,但没有任何反应,它不会出错,但不会显示弹出窗口。 我在这里遗漏了什么吗?如果你需要code.aspx告诉我。
任何帮助都将不胜感激。谢谢!!!
答案 0 :(得分:0)
嘿,请使用此代码
ClientScript.RegisterStartupScript(typeof(Page), "Alert", "script", true);
而不是
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
希望它可以帮助你
答案 1 :(得分:0)
实际上我的方向错误,我需要的是ValidFieldValidator验证控件。请点击这里 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx
谢谢!