试图通过aspx更新db,但它没有将所有字段提交给db(Attempting to update db through aspx but it is not committing all fields to db)
我目前正在构建一个简单的文章库(或博客,无论首选术语是什么)。 目前我可以更新图像,但我遇到了文本问题。 傻傻的,我知道它应该是一个简单的粗暴操作,但解决方案正在回避我的小脑袋。 图像更新正常,但标题和消息字段似乎没有更新,我不知道为什么。 如果其中任何一个有点模糊,我会道歉但是我最终会对此表示怀疑。 它本来应该很简单,我之前做过无数次,但我现在卡住了,感觉有点傻,所以我觉得是时候打电话给SO专家了:)
我的aspx:
<div class="col-sm-10 col-sm-offset-1"> <asp:Label ID="lblError" runat="server"></asp:Label> <asp:FormView ID="frmArticle" runat="server"> <ItemTemplate> <div class="row"> <div class="col-sm-12"> <asp:TextBox ID="txtTitle" Text='<%# Eval("EntryTitle") %>' runat="server" CssClass="form-control"></asp:TextBox> <asp:Image ID="imgOriginal" runat="server" CssClass="img-responsive" ImageUrl='<%# Eval("ImageUrl") %>' /> <asp:FileUpload ID="flupImg" runat="server" AllowMultiple="true" CssClass="form-control" /> <asp:TextBox ID="txtMsg" runat="server" CssClass="form-control" TextMode="MultiLine" Rows="25" Text='<%#Eval("Message")%>' ></asp:TextBox> <div class="row"> <div class="col-sm-6"> <asp:Button ID="btnSubmit" runat="server" Text="Update" CssClass="btn btn-block custBtn" OnClick="btnSubmit_Click" /> </div> <div class="col-sm-6"> <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="btn btn-block custBtn" OnClick="btnCancel_Click" /> </div> </div> </div> </div> </ItemTemplate> </asp:FormView> </div>
我的代码背后:
protected void editPost(string title, string msg) { // Define ADO.NET objects SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("Blog.ttc_BlogPosts", con); cmd.CommandType = CommandType.StoredProcedure; // Define parameters for the Stored procedure cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50)); cmd.Parameters["@Status"].Value = "UpdatePostMessage"; cmd.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = title; cmd.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = msg; cmd.Parameters.Add(new SqlParameter("@EntryId", SqlDbType.Int)); cmd.Parameters["@EntryId"].Value = Convert.ToInt32(Request.QueryString["postid"]); try { con.Open(); // Attempt to open the connection to the db int i = cmd.ExecuteNonQuery(); } catch (SqlException err) { lblError.Text = "Image update error" + err.Message; // Catch exceptions } finally { con.Close(); // Close the connection, even if the attempt to open failed. } } protected void editImg(string imgUrl, string msg, string title) { // Define ADO.NET objects SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("Blog.ttc_BlogPosts", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter adp = new SqlDataAdapter(cmd); // Define parameters for the Stored procedure cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50)); cmd.Parameters["@Status"].Value = "UpdatePostImage"; cmd.Parameters.Add(new SqlParameter("@ImgUrl", SqlDbType.NVarChar, -1)); cmd.Parameters["@ImgUrl"].Value = imgUrl; cmd.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = title; cmd.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = msg; cmd.Parameters.Add(new SqlParameter("@EntryId", SqlDbType.Int)); cmd.Parameters["@EntryId"].Value = Convert.ToInt32(Request.QueryString["postid"]); try { con.Open(); // Attempt to open the connection to the db int i = cmd.ExecuteNonQuery(); } catch (SqlException err) { lblError.Text = "Image update error: " + err.Message; // Catch exceptions } finally { con.Close(); // Close the connection, even if the attempt to open failed. } } protected void btnSubmit_Click(object sender, EventArgs e) { // Find controls TextBox titleFeild = (TextBox)frmArticle.FindControl("txtTitle"); TextBox msgFeild = (TextBox)frmArticle.FindControl("txtMsg"); FileUpload fc = (FileUpload)frmArticle.FindControl("flupImg"); Image postIm = (Image)frmArticle.FindControl("imgOriginal"); // declare variables string aTitle, aMsg; // assign values to variables aTitle = titleFeild.Text; aMsg = msgFeild.Text; // call update functions if (fc.HasFile == false) { editPost(aTitle, aMsg); } else { string file = fc.PostedFile.FileName; // check extension string ext = Path.GetExtension(file); switch (ext.ToLower()) { case ".png": case ".jpg": case ".jpeg": break; default: lblError.Text = "Sorry but this file type is not currently supported."; return; } // Using the following code the file will keep its original name. string sfn = Path.GetFileName(fc.PostedFile.FileName); string fpath = Path.Combine(upDir, sfn); // get name of original file string urlImg = Path.Combine(Request.PhysicalApplicationPath, Server.MapPath(postIm.ImageUrl)); // delete the original file try { File.Delete(urlImg); fc.PostedFile.SaveAs(fpath); editImg(@"~/Images/PostImages/" + sfn, aMsg, aTitle); } catch (IOException ex) { lblError.Text = "Error image: " + ex.Message; } } }
我的存储过程:
CREATE PROCEDURE [Blog].[ttc_BlogPosts] @Status varchar(50) = '' , @EntryId int = '', @Title nvarchar(max) = '', @Added datetime = '', @Updated datetime = '', @Message nvarchar(max) = '', @ImgId int = '', @ImgUrl nvarchar(max) = '' AS BEGIN IF(@Status = 'Display') begin select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited from Blog.BlogEntry order by DateAdded desc end else if(@Status = 'AddPost') begin insert into Blog.BlogEntry (EntryTitle, Message, DateAdded, ImageUrl) values (@Title, @Message, GETDATE(), @ImgUrl) end else if(@Status = 'DisplayPost') begin select EntryTitle, DateAdded, LastEdited, Message, ImageUrl from Blog.BlogEntry where Id = @EntryId end else if(@Status = 'UpdatePost') begin update Blog.BlogEntry set EntryTitle = @Title, Message = @Message, LastEdited = GETDATE() where Id = @EntryId end else if(@Status = 'UpdatePostImage') begin update Blog.BlogEntry set ImageUrl = @ImgUrl, LastEdited = GETDATE(), EntryTitle = @Title, Message = @Message where Id = @EntryId end else if(@Status = 'DeletePost') begin delete from Blog.BlogEntry where Id = @EntryId end END
你们愿意提供的任何帮助都将非常感激。 如果需要任何进一步的细节,请不要犹豫,给我一个喊叫;)
I'm currently building a simple article library (or blog, whatever the preferred term is). At the moment I can update the image fine but I am having trouble with the text. Silly I know as it should be a simple crud operation but a solution is evading my tiny mind. The image updates fine but the title and message fields do not seem to be updating and I have no idea why. Apologies if any of this is a little vague but I am at the end of my wits with this. It should have been simple, I have done it countless times before but I am now stuck and left feeling a little silly, so much so I think its time to call in an SO expert :)
My aspx:
<div class="col-sm-10 col-sm-offset-1"> <asp:Label ID="lblError" runat="server"></asp:Label> <asp:FormView ID="frmArticle" runat="server"> <ItemTemplate> <div class="row"> <div class="col-sm-12"> <asp:TextBox ID="txtTitle" Text='<%# Eval("EntryTitle") %>' runat="server" CssClass="form-control"></asp:TextBox> <asp:Image ID="imgOriginal" runat="server" CssClass="img-responsive" ImageUrl='<%# Eval("ImageUrl") %>' /> <asp:FileUpload ID="flupImg" runat="server" AllowMultiple="true" CssClass="form-control" /> <asp:TextBox ID="txtMsg" runat="server" CssClass="form-control" TextMode="MultiLine" Rows="25" Text='<%#Eval("Message")%>' ></asp:TextBox> <div class="row"> <div class="col-sm-6"> <asp:Button ID="btnSubmit" runat="server" Text="Update" CssClass="btn btn-block custBtn" OnClick="btnSubmit_Click" /> </div> <div class="col-sm-6"> <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="btn btn-block custBtn" OnClick="btnCancel_Click" /> </div> </div> </div> </div> </ItemTemplate> </asp:FormView> </div>
My code behind:
protected void editPost(string title, string msg) { // Define ADO.NET objects SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("Blog.ttc_BlogPosts", con); cmd.CommandType = CommandType.StoredProcedure; // Define parameters for the Stored procedure cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50)); cmd.Parameters["@Status"].Value = "UpdatePostMessage"; cmd.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = title; cmd.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = msg; cmd.Parameters.Add(new SqlParameter("@EntryId", SqlDbType.Int)); cmd.Parameters["@EntryId"].Value = Convert.ToInt32(Request.QueryString["postid"]); try { con.Open(); // Attempt to open the connection to the db int i = cmd.ExecuteNonQuery(); } catch (SqlException err) { lblError.Text = "Image update error" + err.Message; // Catch exceptions } finally { con.Close(); // Close the connection, even if the attempt to open failed. } } protected void editImg(string imgUrl, string msg, string title) { // Define ADO.NET objects SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("Blog.ttc_BlogPosts", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter adp = new SqlDataAdapter(cmd); // Define parameters for the Stored procedure cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50)); cmd.Parameters["@Status"].Value = "UpdatePostImage"; cmd.Parameters.Add(new SqlParameter("@ImgUrl", SqlDbType.NVarChar, -1)); cmd.Parameters["@ImgUrl"].Value = imgUrl; cmd.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = title; cmd.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, -1)); cmd.Parameters["@Title"].Value = msg; cmd.Parameters.Add(new SqlParameter("@EntryId", SqlDbType.Int)); cmd.Parameters["@EntryId"].Value = Convert.ToInt32(Request.QueryString["postid"]); try { con.Open(); // Attempt to open the connection to the db int i = cmd.ExecuteNonQuery(); } catch (SqlException err) { lblError.Text = "Image update error: " + err.Message; // Catch exceptions } finally { con.Close(); // Close the connection, even if the attempt to open failed. } } protected void btnSubmit_Click(object sender, EventArgs e) { // Find controls TextBox titleFeild = (TextBox)frmArticle.FindControl("txtTitle"); TextBox msgFeild = (TextBox)frmArticle.FindControl("txtMsg"); FileUpload fc = (FileUpload)frmArticle.FindControl("flupImg"); Image postIm = (Image)frmArticle.FindControl("imgOriginal"); // declare variables string aTitle, aMsg; // assign values to variables aTitle = titleFeild.Text; aMsg = msgFeild.Text; // call update functions if (fc.HasFile == false) { editPost(aTitle, aMsg); } else { string file = fc.PostedFile.FileName; // check extension string ext = Path.GetExtension(file); switch (ext.ToLower()) { case ".png": case ".jpg": case ".jpeg": break; default: lblError.Text = "Sorry but this file type is not currently supported."; return; } // Using the following code the file will keep its original name. string sfn = Path.GetFileName(fc.PostedFile.FileName); string fpath = Path.Combine(upDir, sfn); // get name of original file string urlImg = Path.Combine(Request.PhysicalApplicationPath, Server.MapPath(postIm.ImageUrl)); // delete the original file try { File.Delete(urlImg); fc.PostedFile.SaveAs(fpath); editImg(@"~/Images/PostImages/" + sfn, aMsg, aTitle); } catch (IOException ex) { lblError.Text = "Error image: " + ex.Message; } } }
My stored procedure:
CREATE PROCEDURE [Blog].[ttc_BlogPosts] @Status varchar(50) = '' , @EntryId int = '', @Title nvarchar(max) = '', @Added datetime = '', @Updated datetime = '', @Message nvarchar(max) = '', @ImgId int = '', @ImgUrl nvarchar(max) = '' AS BEGIN IF(@Status = 'Display') begin select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited from Blog.BlogEntry order by DateAdded desc end else if(@Status = 'AddPost') begin insert into Blog.BlogEntry (EntryTitle, Message, DateAdded, ImageUrl) values (@Title, @Message, GETDATE(), @ImgUrl) end else if(@Status = 'DisplayPost') begin select EntryTitle, DateAdded, LastEdited, Message, ImageUrl from Blog.BlogEntry where Id = @EntryId end else if(@Status = 'UpdatePost') begin update Blog.BlogEntry set EntryTitle = @Title, Message = @Message, LastEdited = GETDATE() where Id = @EntryId end else if(@Status = 'UpdatePostImage') begin update Blog.BlogEntry set ImageUrl = @ImgUrl, LastEdited = GETDATE(), EntryTitle = @Title, Message = @Message where Id = @EntryId end else if(@Status = 'DeletePost') begin delete from Blog.BlogEntry where Id = @EntryId end END
Any help that you guys are willing to offer will be very much appreciated. If any further details are required please do not hesitate to give me a shout ;)
原文:https://stackoverflow.com/questions/32178762
最满意答案
以相反的顺序迭代它,只删除不等于当前项目的项目。
var current = 2; var i = 0; for (i=itemsAll-1;i>=0;i--) { if (i != current) { removeItem(i); } }
我可能应该说明反向循环的原因。 Hans评论说,循环是反向完成的,因为'removeItem'可能导致剩余的项目被重新编号。
Iterate over it in reverse order and only remove the items which does not equal the current item.
var current = 2; var i = 0; for (i=itemsAll-1;i>=0;i--) { if (i != current) { removeItem(i); } }
I probably should have stated the reason for the reverse loop. As Hans commented, the loop is done in reverse because the 'removeItem' may cause the remaining items to be renumbered.
相关问答
更多-
你能在if-else语句的条件下使用for循环吗?(Can you use a for loop inside the condition of an if-else statement?)[2022-08-22]
你应该首先解决你的情况(即按顺序排列你的数组),然后将其输入你的if语句。 像这样...... boolean isOrdered = true; for(q = 0; q < 10; q++){ if (values[q]>=values[q+1]){ // in order } else { // not in order isOrdered = false; break; // we have found a false, so we can quit ... -
一个开关构造更容易被转换成一个跳转(或分支)表 。 当case标签靠近在一起时,这可以使switch语句比if-else更有效。 这个想法是将一堆跳转指令顺序放在内存中,然后将该值添加到程序计数器。 这将替换一系列比较指令与添加操作。 以下是一些非常简化的伪装组件示例。 首先,if-else版本: // C version if (1 == value) function1(); else if (2 == value) function2(); ...
-
在分配语句中使用长嵌套if-else是一种不好的做法吗?(Is a bad practice to use long nested if-else in assign statement?)[2021-11-27]
格式化 嵌套的条件连续赋值没有任何问题,但有一些方法使其更具可读性: assign a = (b) ? '1 : (c&d) ? '0 : (f&h) ? '1 : '0; 然而,这仍然是一个“if ... else if ... else if ... else”的结构,你应该问自己的问题是这个代码的意图是什么以及它会如何“读取”。 如果使用always和“”if ... else if ... else if ... e ... -
使用do-while循环和if-else语句进行双重验证(Dual validation with a do-while loop and if-else statement)[2022-11-16]
而不是do-while循环,我喜欢使用无限循环+ break语句的组合,如下所示: cout << "What is your first choice? "; while (true) { // Input the choice, including validation // Do the move if (game_over) break; cout << "Interesting move; what is your next choice? " ... -
布尔表达式本身的问题是它们总是为True。 if a == 'b' or 'c'就像if (True|False) or 'c' ,并且因为'c'是真实的 ,所以无论第一个表达式( a == 'b' )如何都是真的。 你想要a == 'b' and a == 'c'…或者更简洁的a in {'b', 'c'…} ,它会检查a是否是该集合的成员。 如果你想循环,使用循环:) while username not in {"cking", "doneal", "mcook"}: print ("Inva ...
-
嵌套for-each和if-else语句没有goto语句(Nested for-each and if-else statement without goto statement)[2023-12-19]
如果你的方法很长,这是一种难闻的气味。 将其分解为更小的方法或更小的类。 这将使它更容易跳到另一个位置。 也许状态机原理将帮助你设置下一个状态。 If your method is that long, it is a bad smell. Break it into smaller methods or smaller classes. That will makes it also easier to jump to an other position. Maybe state machine prin ... -
这里是关于三元运算符的一些信息,它的用途是: ?: Operator (C#) 你想做什么是不可能的......它不是如何工作的。 Here is some information on the ternary operator and it's uses: ?: Operator (C#) What you want to do is just impossible... it's not how it works.
-
for循环与if-else语句(for Loop with if-else statement)[2023-03-20]
以相反的顺序迭代它,只删除不等于当前项目的项目。 var current = 2; var i = 0; for (i=itemsAll-1;i>=0;i--) { if (i != current) { removeItem(i); } } 我可能应该说明反向循环的原因。 Hans评论说,循环是反向完成的,因为'removeItem'可能导致剩余的项目被重新编号。 Iterate over it in reverse order and only remove the ... -
您不需要遍历结果,因为您只需要最多一行。 我会这样做: using (var cmd = sc.CreateCommand()) { cmd.CommandText = "select 1 from Students where Username=.. and Password= .."; if (cmd.ExecuteScalar() != null) { // username and password matched a user } else { // ...
-
你只是缺少一些空间...... #!/bin/bash a="ACC_A" b="ACC_B" c="ACC_C" d="ACC_D" USERS="ACC_A ACC_B ACC_C ACC_X ACC_Y ACC_Z" for ACCOUNT in $USERS; do if [ "$ACCOUNT" = "$a" ] || [ "$ACCOUNT" = "$b" ] || [ "$ACCOUNT" = "$c" ] || [ "$ACCOUNT" = "$d" ]; then ...