【问题标题】:Image upload not working Always get the FALSE value图片上传不工作总是得到 FALSE 值
【发布时间】:2016-09-25 08:52:18
【问题描述】:

用户界面 图片上传部分不起作用,我想在数据库中上传图片路径但不起作用,并且没有正确绑定无法保存,请您帮帮我,表格显示的上传图片值总是FALSE ASPX

<asp:TemplateField HeaderText="Images">
   <ItemTemplate>
      <asp:FileUpload runat="server"  AutoPostBack="True"  ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
   </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
   <ItemTemplate>
      <asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="image"  Width="40" Height="40"/>
   </ItemTemplate>
</asp:TemplateField>

代码

     #region Detail Save1
        private DataTable CreateDetailSave()
        {
            DataTable dtDetailSave1 = new DataTable();
            DataColumn dc1;
            dc1 = new DataColumn("intArticleDetailId");
            dtDetailSave1.Columns.Add(dc1);
            dc1 = new DataColumn("intSectionId");
            dtDetailSave1.Columns.Add(dc1);
            dc1 = new DataColumn("intCompoundId");
            dtDetailSave1.Columns.Add(dc1);            
            dc1 = new DataColumn("decSectionWeight");
            dtDetailSave1.Columns.Add(dc1);
            dc1 = new DataColumn("intMessageId");
            dtDetailSave1.Columns.Add(dc1);
            dc1 = new DataColumn("strImage");
            dtDetailSave1.Columns.Add(dc1);

            foreach (GridViewRow row in gvArticle.Rows)
            {
                DataRow dr = dtDetailSave1.NewRow();

                Label lblintArticleDetailId = (Label)row.FindControl("lblArticleDetailId");
                Label lblSectionId = (Label)row.FindControl("lblSectionId");
                DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
                TextBox txtdecSectionWeighte = (TextBox)row.FindControl("txtdecSectionWeighte");
                DropDownList intMessage = (DropDownList)row.FindControl("ddlMessage");

                FileUpload fileupload = (FileUpload)row.FindControl("fileupload");

                dr["intArticleDetailId"] = CurrentMode == "Add" ? -1 : Convert.ToInt32(lblintArticleDetailId.Text);

                dr["intSectionId"] = Convert.ToInt32(lblSectionId.Text);
                dr["intCompoundId"] = ddlCompound.SelectedValue;
                dr["decSectionWeight"] = txtdecSectionWeighte.Text.Trim() != "" ? Convert.ToDecimal(txtdecSectionWeighte.Text.Trim()) : 0;
                dr["intMessageId"] = intMessage.SelectedValue;
                dr["strImage"] = fileupload.HasFile;

                dtDetailSave1.Rows.Add(dr);
            }
            return dtDetailSave1;
        }
        #endregion

         #region pageload
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {

                ClearControls();

                FillArticleDetails();

                EnableControls(false);
                Session["SearchPopup"] = false;

            }
            else
            {
                if (Session["SearchPopup"] != null)
                {
                    SearchPopup = (bool)(Session["SearchPopup"]);
                    if (SearchPopup != false)
                    {
                        MyMPE.Show();
                    }
                    else
                    {
                        MyMPE.Hide();
                    }
                }

                vAdSearchParaList = new List<SearchParametors>();

            }
        }
        #endregion
 #region Create Article table
        private void createArticleDataTable()
        {
            if (dt.Columns.Count == 0)
            {
                dt.Columns.Add(new DataColumn("intArticleDetailId", typeof(int)));
                dt.Columns.Add(new DataColumn("intSectionId", typeof(int)));
                dt.Columns.Add(new DataColumn("strSectionName", typeof(string)));
                dt.Columns.Add(new DataColumn("intCompoundId", typeof(string)));
                dt.Columns.Add(new DataColumn("decSectionWeight", typeof(string)));
                dt.Columns.Add(new DataColumn("intMessageId", typeof(string)));
                dt.Columns.Add(new DataColumn("fileupload", typeof(string)));

            }

            gvArticle.DataSource = dt;
            gvArticle.DataBind();
        }        
        #endregion

        #region Compound Grid - Add empty row
        private void ArticleGridAddEmptyRow(int newId)
        {
            DataRow newDr = null;
            newDr = dt.NewRow();
            newDr["intArticleDetailId"] = 1;
            newDr["intSectionId"] = 1;
            newDr["strSectionName"] = "";
            newDr["intCompoundId"] = "";
            newDr["decSectionWeight"] = "";
            newDr["intMessageId"] = "";
            newDr["strImage"] = "";

            dt.Rows.Add(newDr);

            if (dtArticleDetails == null || dtArticleDetails.Rows.Count == 0)
            {
                dtArticleDetails = dt;
            }
            else
            {
                dtArticleDetails.Merge(dt);

                gvArticle.DataSource = dt;
                gvArticle.DataBind();
            }
        }
        #endregion

protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = gvArticle.Rows[e.RowIndex];
            FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
            if (fu != null && fu.HasFile)
            {
                fu.SaveAs(Server.MapPath("~/Uploaded Images" + fu.FileName));
            }
        }

全aspx

                    <asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" CssClass="table table-bordered table-condensed table-hover" AutoGenerateColumns="False" runat="server" AllowPaging="True" PageSize="15" OnRowDataBound="gvArticle_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" OnRowUpdating="gvArticle_RowUpdating">
                                                 <%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
                                                            <Columns>
                                                                <asp:TemplateField HeaderText="intArticleDetail" Visible="false">
                                                                    <ItemTemplate>
                                                                        <asp:Label ID="lblArticleDetailId" Width="2" Text='<%# Bind("intArticleDetailId") %>' ClientIDMode="Static" runat="server"></asp:Label> 
                                                                    </ItemTemplate>
                                                                </asp:TemplateField> 

                                                                <asp:TemplateField HeaderText="SectionID" Visible="false">
                                                                     <ItemTemplate>
                                                                        <asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label> 
                                                                     </ItemTemplate>
                                                                </asp:TemplateField>                                                        

                                                                <asp:TemplateField HeaderText="Section">
                                                                    <ItemTemplate>
                                                                        <asp:Label ID="lblSectionName" Width="100"  Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label> 
                                                                    </ItemTemplate>
                                                                </asp:TemplateField>  
                                                                <asp:TemplateField HeaderText="Compound">
                                                                        <EditItemTemplate>
                                                                            <asp:Label ID="lblItemTypeEdit" Width="50" Text='<%# Bind("strCompoundName") %>' lientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
                                                                            </asp:Label>
                                                                        </EditItemTemplate>

                                                                        <ItemTemplate>
                                                                            <asp:DropDownList ID="ddlCompoundId" Width="200" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
                                                                            </asp:DropDownList>
                                                                        </ItemTemplate>
                                                                 </asp:TemplateField>


                                                                <asp:TemplateField HeaderText="Weight">
                                                                    <ItemTemplate>
                                                                        <asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' lientIDMode="Static" runat="server">  </asp:TextBox>                                                                            
                                                                    </ItemTemplate>
                                                                </asp:TemplateField>

                                                                <%--<asp:TemplateField HeaderText="Messagers">                                                                
                                                                    <ItemTemplate>
                                                                        <asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
                                                                    </ItemTemplate>
                                                                </asp:TemplateField>--%>

                                                                 <asp:TemplateField HeaderText="Messagers">
                                                                        <EditItemTemplate>
                                                                            <asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
                                                                            </asp:Label>
                                                                        </EditItemTemplate>

                                                                        <ItemTemplate>
                                                                            <asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
                                                                            </asp:DropDownList>
                                                                        </ItemTemplate>
                                                                 </asp:TemplateField>

                                                                <asp:TemplateField HeaderText="Images">                                                                
                                                                    <ItemTemplate>


                                                              <asp:FileUpload runat="server"  AutoPostBack="True"  ID="uploadFImage" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>

                                                                    </ItemTemplate>
                                                                </asp:TemplateField> 


                                                                   <asp:TemplateField HeaderText="">                                                                
                                                                    <ItemTemplate>


  <asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage"  Width="40" Height="40"/>

                                                                    </ItemTemplate>
                                                                </asp:TemplateField> 

                                                            </Columns>

                                                 <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                                                 <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                                                 <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                                                 <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                                                 <SortedAscendingCellStyle BackColor="#F7F7F7" />
                                                 <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
                                                 <SortedDescendingCellStyle BackColor="#E5E5E5" />
                                                 <SortedDescendingHeaderStyle BackColor="#242121" />

                                            </asp:GridView>    
                                        </div>
  </ContentTemplate>
       <Triggers>           
            <asp:PostBackTrigger ControlID="gvArticle"/> 
           </Triggers>

                                    </asp:UpdatePanel> 
                                    </div>
                                </div>

gvArticle_rowdatabound

protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {


            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {


                { 


                }

                DataTable CompoundCode = clsArticle.CompoundDataForGrid("");

                DropDownList ddlCompoundId = (DropDownList)e.Row.FindControl("ddlCompoundId");
                if (ddlCompoundId != null)
                {
                    ddlCompoundId.DataTextField = "Compound Code";
                    ddlCompoundId.DataValueField = "Compound Id";
                    ddlCompoundId.DataSource = CompoundCode;
                    ddlCompoundId.DataBind();

                    string country = (e.Row.FindControl("ddlCompoundId") as DropDownList).Text;
                    ddlCompoundId.Items.FindByValue(country).Selected = true;
                }


                DataTable MsgCode = clsArticle.MessageDataForGrid("");

                DropDownList ddlMessage = (DropDownList)e.Row.FindControl("ddlMessage");
                if (ddlMessage != null)
                {
                    ddlMessage.DataTextField = "Message Name";
                    ddlMessage.DataValueField = "Message Id";
                    ddlMessage.DataSource = MsgCode;
                    ddlMessage.DataBind();

                    ddlMessage.Items.Insert(0, new ListItem("Please select"));
                    string country = (e.Row.FindControl("ddlMessage") as DropDownList).Text;
                    ddlMessage.Items.FindByValue(country).Selected = true;
                }



                //}


            }
        }

【问题讨论】:

  • 链接中的代码:wklej.to/dFXXf
  • 先生,我添加了这个,我上传了图像并调试我得到了一个我的表,下面有一个符号“>”我添加了屏幕截图
  • 检查此代码&lt;asp:TextBox ID="txtstrImage" Width="100%" CommandArgument='&lt;%# Eval("strImage") %&gt;' ClientIDMode="Static" runat="server" visible="False"&gt; &gt; &lt;/asp:TextBox&gt;。我可以看到它
  • 这个问题需要清理一下。首先,您应该真的清理代码部分。 NOT 要求您修复降价以便代码部分在屏幕上实际上是理智的。其次,您的屏幕截图显示调试器位于名称以sa 开头的方法中,大概是saveArticle 或类似名称。但是问题中没有这种方法。如果我们必须猜测您的代码是什么样的,我们怎么可能给出好的答案?
  • 将布尔值HasFile 放在文件的字符串值中是否正常? (dr["strImage"] = fileupload.HasFile;)

标签: c# asp.net gridview


【解决方案1】:

您的代码有很多问题。 首先FileUpload 控件没有AutoPostBack 属性和CommandArgument 属性,因此您需要在每一行中都有一个按钮。

.aspx 片段

<asp:TemplateField HeaderText="upload">
    <ItemTemplate>
        <asp:FileUpload ID="fileupload" AutoPostBack="true"  runat="server" />
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="upload">
    <ItemTemplate>
        <asp:Button ID="btnUpdate" Text="upload" OnClick="btnUpdate_Click" CommandArgument='<%#Eval("PK_FIELD") %>' runat="server" />
    </ItemTemplate>
</asp:TemplateField>

.aspx.cs 片段

protected void btnUpdate_Click(object sender, EventArgs e)
{
    FileUpload fu = 
      ((GridViewRow)((WebControl)sender).NamingContainer)
          .FindControl("fileupload") as FileUpload;
    bool ok = false;
    if (fu != null && fu.HasFile)
    {
        try
        {
            //possible issue here.
            //process NEED PERMISSION to write to this folder
            //also some checks with fu.PostedFile are recommended
            fu.SaveAs(Server.MapPath("~/images/" + fu.FileName));
            ok = true;
        }
        catch (Exception ex)
        {
            ok = false;
        }
    }
    if (ok)
    {
        //update DB table and GridViewRow image field.
    }
}

我希望这个解释是有用的和可接受的。

根据您的 gridview 更新

    <asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" CssClass="table
     table-bordered table-condensed table-hover" AutoGenerateColumns="False"
     runat="server" AllowPaging="True" PageSize="15" 
    OnRowDataBound="gvArticle_RowDataBound" 
 DataKeyNames="PK_field"  **important**
    >
        <%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
        <Columns>
            <asp:TemplateField HeaderText="intArticleDetail" Visible="false">
            <ItemTemplate>
               <asp:Label ID="lblArticleDetailId" Width="2" 
Text='<%# Eval("intArticleDetailId") %>' **Bind is nonsense for label**
 runat="server"></asp:Label> **ClientIDMode="Static" remove everiwhere**
            </ItemTemplate>
            </asp:TemplateField> 

            <asp:TemplateField HeaderText="SectionID" Visible="false">
                 <ItemTemplate>
                    <asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label> 
                 </ItemTemplate>
            </asp:TemplateField>                                                        
        <asp:TemplateField HeaderText="Section">
            <ItemTemplate>
                <asp:Label ID="lblSectionName" Width="100"  Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label> 
            </ItemTemplate>
        </asp:TemplateField>  
        <asp:TemplateField HeaderText="Compound">
            <EditItemTemplate>** no edit mode remove**
                <asp:Label ID="lblItemTypeEdit" Width="50" 
Text='<%# Bind("strCompoundName") %>' ** see above**
ClientIDMode="Static" 
AutoPostBack="true" 
runat="server">                                                                               
                </asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="ddlCompoundId" Width="200" 
    CssClass="form-control my-DropDownThin" ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
                </asp:DropDownList>
            </ItemTemplate>
         </asp:TemplateField>
    <asp:TemplateField HeaderText="Weight">
    <ItemTemplate>
    <asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' ClientIDMode="Static" runat="server">  </asp:TextBox>                                                                            
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Messagers">                                                                
    <ItemTemplate>

    <asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
    </ItemTemplate>
</asp:TemplateField>--%>

        <asp:TemplateField HeaderText="Messagers">
    <EditItemTemplate>
    <asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
    </asp:Label>
    </EditItemTemplate>

        <ItemTemplate>
    <asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
    </asp:DropDownList>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Images">                                                                <ItemTemplate>
**work with upload. remove wrong attributes**
**AutoPostBack="True"CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static" ** 
          <asp:FileUpload runat="server" ID="uploadFImage" />
</ItemTemplate>
</asp:TemplateField> 
<asp:TemplateField HeaderText="">                                                                
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage"  Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField> 
</Columns>


     <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
     <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
     <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
     <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
     <SortedAscendingCellStyle BackColor="#F7F7F7" />
     <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
     <SortedDescendingCellStyle BackColor="#E5E5E5" />
     <SortedDescendingHeaderStyle BackColor="#242121" />

</asp:GridView>    
** place update button outside to update all columns **
<asp:Button ID="btnUpdate" Text="upload" OnClick="btnUpdate_Click" runat="server" />

//.aspx.cs
    protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gvArticle.rows)
{

    FileUpload fu = 
          row.FindControl("fileupload") as FileUpload;
    bool ok = false;
    if (fu != null && fu.HasFile)
    {
        try
        {
            //possible issue here.
            //process NEED PERMISSION to write to this folder
            //also some checks with fu.PostedFile are recommended
            fu.SaveAs(Server.MapPath("~/images/" + fu.FileName));
            ok = true;
        }
        catch (Exception ex)
        {
            ok = false;
        }
    }
    if (ok)
    {
        //update DB table and GridViewRow image field.
    }
}
}

【讨论】:

  • 先生,不工作,我累了,我尝试了所有的代码,但还是不行,谢谢你的帮助
  • 你能显示错误信息吗?还将throw ex; 添加到catch 块中。
  • 重新开始。 FileUpload 没有 AutoPostBackCommandAttribute。您的代码中没有任何内容可以触发回发。没有切换到编辑模式,因此无法访问 gvArticle_RowUpdating。如果你奇迹般地到达那里,你的FileUpload不在编辑模板中。
  • 先生,我该怎么做
【解决方案2】:

您尝试使用与您阅读的路径不同的路径保存它:Server.MapPath("~/Uploaded Images" + fu.FileName) != &lt;asp:Image ImageUrl="~/Uploaded Images/Default.png" 注意在保存路径中缺少 /。试试这个代码:

protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
   GridViewRow row = gvArticle.Rows[e.RowIndex];
   FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
   if (fu != null && fu.HasFile)
   {
       fu.SaveAs(Server.MapPath("~/Uploaded Images/" + fu.FileName));

   }
}

【讨论】:

    【解决方案3】:

    当使用 FileUpload Control 选择文件时,postback, PostedFile 属性将使用文件的 HttpPostedFile 对象初始化。由于http request 不能保持状态,所以它失去了它的状态。

    FileUpload 控件不适用于asynchronous postback。因此需要postback 来获取文件。一种方法是为您的Upload 按钮设置triggers

    为了保持文件上传控制的价值,您可以将文件上传对象完全存储在session 中,并在postback 之后从会话中检索您需要的值。

    编辑:尝试使用以下example.

    【讨论】:

    • 先生,我尝试总是错误的
    • 这个对象是 null ` dr["strImage"] = fileupload.HasFile;` 我认为这是 HasFile 的问题
    • @PhantomAssassin 你能在页面加载中发布相同的代码并检查它是否有价值吗?
    【解决方案4】:

    您正在使用 RowUpdating 所以我的建议是使用 EditItemTemplateItemTemplate 所以添加这个

    <EditItemTemplate>
        <asp:FileUpload runat="server"  AutoPostBack="True"  ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
    </EditItemTemplate>
    

    还有这个:-

    <ItemTemplate>
        <asp:FileUpload runat="server"  AutoPostBack="True"  ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
    </ItemTemplate>
    

    所以您的TemplateField 图像将如下所示

    <asp:TemplateField HeaderText="Images">
        <ItemTemplate>
            <asp:FileUpload runat="server"  AutoPostBack="True"  ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:FileUpload runat="server"  AutoPostBack="True"  ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
       </EditItemTemplate>
    </asp:TemplateField>
    

    对于 Lesmian 所说的文件上传,请使用:-

    protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                GridViewRow row = gvArticle.Rows[e.RowIndex];
                FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
                if (fu != null && fu.HasFile)
                {
                    fu.SaveAs(Server.MapPath("~/Uploaded Images/" + fu.FileName));
                }
            }
    

    希望这会对你有所帮助。

    【讨论】:

    • 我试试这个,不工作先生,总是把路径弄错
    • @PhantomAssassin 你能粘贴整个网格视图 html
    • @PhantomAssassin 在您的代码中,您将绑定您的网格视图gvArticle 从您调用这些函数的位置
    • 先生,我添加代码,你能检查一下吗,fullaspx
    • 先生,在gvArticle_RowUpdating
    【解决方案5】:

    在 aspx 页面中,使用 updatepanel 控件来保存生成的 ID。 参考以下代码。

    < asp:TemplateField HeaderText=""> 
      < ItemTemplate>              
       <asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="fileUploadPanel">           
         <ContentTemplate>
           <asp:FileUpload runat="server"  AutoPostBack="True"  ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
         </ContentTemplate>                                                             
         <Triggers>                                                             
          <asp:PostBackTrigger ControlID="fileupload" />    
        </Triggers>                                                 
      </asp:UpdatePanel>                                             
     </ItemTemplate>
    
    <ItemTemplate>                                                 
     <asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="ImageUploadPanel">  
      <ContentTemplate>                                         
        <asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="image"  Width="40" Height="40"/>                       
      </ContentTemplate>                                    
      <Triggers>                                              
       <asp:PostBackTrigger ControlID="image" />            
     </Triggers>                                  
     </asp:UpdatePanel>                     
    </ItemTemplate>                     
    < /asp:TemplateField>
    

    希望这会有所帮助..

    【讨论】:

      【解决方案6】:

      给定的代码有一些严重的错误,也不完整。在我的结尾真的很难重现。无论如何,有一些事情可以解决这个问题:

      • 删除不必要的代码,例如包含AutopostBack="true" 的标签。
      • Gridview 中的ClientIdMode="static" 会生成无效的 HTML,这可能是您的问题的原因,因为它会生成具有相同 id 值的 HTML 元素,并且会创建无效的 HTML 页面。有不同的代码行包含这个属性。只需删除这些即可。
      • 第三个是你的aspx代码行&lt;asp:PostBackTrigger ControlID="gvArticle"/&gt;。它应该指向一个按钮控件,该控件会在您选择图像后导致回发。我认为,这里应该使用保存按钮 ID。

      修改你的代码还是没有解决,你需要提供整页代码来做更多的诊断。 享受吧!

      【讨论】:

        【解决方案7】:

        您几乎总是会得到一个布尔值 (false),因为您设置了 strImage 值。

        dr["strImage"] = fileupload.HasFile;

        在 foreach 下检查你的代码。

        此外,在 gvArticle_RowUpdating() 事件下,您会发现 fileupload 控件的值是 strImage 而不是使用您定义的 id @987654324 @

        protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                GridViewRow row = gvArticle.Rows[e.RowIndex];
                FileUpload fu = row.Cells[0].FindControl("fileupload") as FileUpload;
                if (fu != null && fu.HasFile)
                {
                    fu.SaveAs(Server.MapPath("~/Uploaded Images" + fu.FileName));
                }
            }
        

        【讨论】:

        • @Codeone,你在page_load上绑定了gridview吗?此外,HasFile 属性为假,但实际的文件数据呢?它是 null,还是有值?
        【解决方案8】:

        正如@Ruban.J 所说“FileUpload 控制不适用于异步回发” 意味着它总是与UpdatePanel 有一些问题,每当Postback 发生fileupload 丢失它时,它会声明[其文件],

        他还说 为了保持文件上传控制的价值,您可以将文件上传对象完全存储在会话中,并在回发后从会话中检索您需要的值。

        所以将所有过程分解成小步骤

        第 1 步:您必须在回发发生时将所有 fileupload 对象保存到会话中,为此我认为这应该适用于 pageLoad 事件。

         if (!IsPostBack)
                    {
                        //Bind your gridview 1st time
        
                    }
                    else
                    {
                        Dictionary<int, HttpPostedFile> postedFiles = new Dictionary<int, HttpPostedFile>();
        
                        foreach (GridViewRow row in gvArticle.Rows)
                        {
        
                            int id = Convert.ToInt16("YourUniqueRowId"); // whaterver your unique id is there
                            DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
                            // find your fileupload controll for that row         
                            FileUpload fileupload = (FileUpload)row.FindControl("fileupload");
                            if (fileupload.HasFile)
                            {
                                postedFiles.Add(id, fileupload.PostedFile);
                            }
        
        
                        }
                        Session["files"] = postedFiles;
                    } 
        

        还可以通过查看每个HttpPostedFile 来检查您是否在此处获取文件信息。

        第 2 步:当您需要文件时,只需从会话中获取它:

        if (Session["files"] != null)
        {
            Dictionary<int, HttpPostedFile> postedFiles = (Dictionary<int, HttpPostedFile>) Session["files"];
        }
        

        你可以匹配Key值来决定哪个文件对应哪一行,并保存到数据库中。

        【讨论】:

          【解决方案9】:

          我认为在foreach 循环内的CreateDetailSave 方法中,您将filename 保存为fileupload.Hasfile,它将始终返回真或假。这就是为什么它总是返回 false:

          foreach (GridViewRow row in gvArticle.Rows)
          {
              dr["strImage"] = fileupload.filename;         //before it was fileupload.Hasfile
          }
          

          【讨论】:

          • 先生,我在没有得到假值后尝试这个,只得到空值
          【解决方案10】:

          尝试更改 FileUpload 控件中的 ClientIDMode = Inherit 并检查它是否正常工作。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-14
            • 2017-01-01
            • 2011-11-08
            • 1970-01-01
            • 2010-11-19
            • 2016-11-12
            相关资源
            最近更新 更多