首页 \ 问答 \ 试图通过aspx更新db,但它没有将所有字段提交给db(Attempting to update db through aspx but it is not committing all fields to db)

试图通过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
更新时间:2023-09-05 17:09

最满意答案

以相反的顺序迭代它,只删除不等于当前项目的项目。

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.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)