Ссылка на объект не установлена на экземпляр объекта ASP.NET ошибка
Я попытался найти ответы на вопрос, Как сохранить загруженные изображения с помощью ajaxfileupload и сохранить их в базе данных, и я нашел несколько возможных решений. Я интегрировал эти коды и уже протестировал код в небольшой программе, и все работает нормально. Но когда я включаю его в свой реальный проект, он не работает и выдает мне ошибку, которая говорит: "ссылка на объект не установлена на экземпляр объекта". Новый фрагмент кода, который я интегрировал, - это AJAX-скрипт, который будет запущен в OnClientUploadComplete, а также элементы управления ajaxfileupload. Пожалуйста, смотрите подробную информацию ниже для получения дополнительной информации.
Вот aspx(я включил все в свой код, но главное, что вы должны посмотреть, это два ajaxfileupload, которые имеют идентификатор itemFileUpload1 и itemFileUpload2 и AJAX-скрипт выше):
Что я уже пробовал:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateBrands.aspx.cs" Inherits="Pages_CreateBrands" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp"%> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Music Store</title> <script src="../Javascript/jquery-1.11.2.min.js"></script> <script type="text/javascript"> function uploadComplete(sender, args) { var txt = document.getElementById("validatePicture");//Your hiddenfield id txt.value = "1"; $.ajax({ type: "post", url: "OpenPost.aspx/GetPath", contentType: "application/json; charset=utf-8", dataType: "json", success: function (result1,result2) { OnSuccess1(result1.d,result2.d); }, error: function (xhr, status, error) { OnFailure1(error); } }); } function OnSuccess1(result1,result2) { var pp1 = document.getElementById("PicturePath1"); pp1.value = result1; var pp2 = document.getElementById("PicturePath2"); pp2.value = result2; } function OnFailure1(error) { alert(error); } </script> <link rel="stylesheet" href="~/Styles/jquery.bxslider.css"/> <link rel="stylesheet" href="~/Styles/StyleSheet.css"/> <link rel="stylesheet" href="~/Styles/font-awesome.min.css"/> <link rel="shortcut icon" type="image/png" href="~/Images/rockSign.png"/> <style type="text/css"> .auto-style1 { width: 160px; height: 37px; } .auto-style2 { height: 37px; } </style> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div id="wrapper"> <header id="main_header"> <div id="callout"> <h2>☎ 111222333</h2> <p>Michigan State Kawasaki Iceland</p> </div> <h1>MUSIC STORE</h1> </header> <div class="clearfix"></div> <nav id="nav_menu"> <ul id="nav"> <li><a href="~/Pages/Home.aspx" runat="server">HOME</a></li> <li><a href="#">INSTRUMENTS</a> <ul class="sub-menu"> <li><a href="~/Pages/GuitarBrands.aspx" runat="server">ELECTRIC GUITARS</a></li> <li><a href="~/Pages/BassGuitarBrands.aspx" runat="server">BASS GUITARS</a></li> <li><a href="#">DRUMS</a></li> </ul> </li> <li><a href="#">AMPLIFIERS</a></li> <li><a href="#">ACCESSORIES</a></li> <li><a href="#">FEATURED ARTISTS</a></li> <li><a href="#"><img src="../Images/cog.png" /></a> <ul class="cog_submenu"> <li><a href="~/Pages/CreateBrands.aspx" runat="server">CREATE NEW BRAND</a></li> <li><a href="#">USE EXISTING BRAND</a></li> <li><a href="~/Pages/OverviewGuitarData.aspx" runat="server">GUITAR DATA OVERVIEW</a></li> <li><a href="~/Pages/OverviewBassData.aspx" runat="server">BASS DATA OVERVIEW</a></li> </ul> </li> </ul> </nav> <div id="content_area"> <h3> </h3> <h3 class="headingTitle">Create New Brand(Step 1 of 2):</h3> <table cellspacing="15" class="brandsTable"> <tr> <td style="width: 160px; height: 37px;"> Brand Type:</td> <td style="height: 37px"> <asp:CheckBox ID="brandTypeGuitar" runat="server" Text="Guitar" AutoPostBack="True" GroupName="brandType"/> <asp:CheckBox ID="brandTypeBass" runat="server" Text="Bass" AutoPostBack="True" GroupName="brandType"/> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Brand Name:</td> <td style="height: 37px"> <asp:TextBox ID="brandName" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td class="auto-style1"> Brand Image:</td> <td class="auto-style2"> <br/> <asp:FileUpload ID="brandFileUpload" runat="server" /> <asp:Button ID="brandUploadImage" runat="server" Text="Upload Image" OnClick="brandUploadImage_Click" /> </td> </tr> </table> <asp:Label ID="lblResult" runat="server" Text=""></asp:Label> <br /> <asp:Button ID="btnSave" runat="server" CssClass="submitButton" Text="Save Brand" OnClick="btnSave_Click" /> <br/> <br/> <h3 class="headingTitle">Create New Item(Step 2 of 2):</h3> <table cellspacing="15" class="brandsTable"> <tr> <td style="width: 160px; height: 37px;"> Item Type:</td> <td style="height: 37px"> <asp:RadioButton ID="itemType1" runat="server" Text="Guitar" AutoPostBack="False" GroupName="ItemType"/> <asp:RadioButton ID="itemType2" runat="server" Text="Bass" AutoPostBack="False" GroupName="ItemType"/> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Brand:</td> <td style="height: 37px"> <asp:TextBox ID="itemBrand" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Model:</td> <td style="height: 37px"> <asp:TextBox ID="itemModel" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Price:</td> <td style="height: 37px"> <asp:TextBox ID="itemPrice" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Image1:</td> <td style="height: 37px"> <br /> <asp:AjaxFileUpload ID="itemFileUpload1" runat="server" OnUploadComplete="itemUploadImage1_Click" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1"/> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Image2:</td> <td style="height: 37px"> <br /> <asp:AjaxFileUpload ID="itemFileUpload2" runat="server" OnUploadComplete="itemUploadImage2_Click" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1"/> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Description:</td> <td style="height: 37px"> <asp:TextBox ID="itemDescription" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Neck Type:</td> <td style="height: 37px"> <asp:TextBox ID="itemNeckType" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Body:</td> <td style="height: 37px"> <asp:TextBox ID="itemBody" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Fretboard:</td> <td style="height: 37px"> <asp:TextBox ID="itemFretboard" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Fret:</td> <td style="height: 37px"> <asp:TextBox ID="itemFret" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Bridge:</td> <td style="height: 37px"> <asp:TextBox ID="itemBridge" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Neck Pickup:</td> <td style="height: 37px"> <asp:TextBox ID="itemNeckPickup" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Bridge Pickup:</td> <td style="height: 37px"> <asp:TextBox ID="itemBridgePickup" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> <tr> <td style="width: 160px; height: 37px;"> Item Hardware Color:</td> <td style="height: 37px"> <asp:TextBox ID="itemHardwareColor" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox> </td> </tr> </table> <asp:Label ID="lblResult2" runat="server" Text=""></asp:Label> <br /> <asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save Item" OnClick="Button1_Click"/> </div> <div class="clearfix"></div> <footer> <p>©All Rights Reserved</p> </footer> </div> </form> </body> </html>
Вот код-за. Я также включил все в файл aspx. cs. Главное, на чем вы должны сосредоточиться, - это метод itemUploadImage1_Click, itemUploadImage2_Click и Button1_Click. Ошибка начинается в Button1_Click, который указывает на строку item_image1 и item_image2, указывая, что она равна null;
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using AjaxControlToolkit; public partial class Pages_CreateBrands : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private void ClearTextFields() { brandName.Text = ""; } private void ClearTextFields2() { itemBrand.Text = ""; itemModel.Text = ""; itemPrice.Text = ""; itemDescription.Text = ""; itemNeckType.Text = ""; itemBody.Text = ""; itemFretboard.Text = ""; itemFret.Text = ""; itemNeckPickup.Text = ""; itemBridgePickup.Text = ""; itemBridge.Text = ""; itemHardwareColor.Text = ""; } protected void brandUploadImage_Click(object sender, EventArgs e) { try { string filename = Path.GetFileName(brandFileUpload.FileName); brandFileUpload.SaveAs(Server.MapPath("~/Images/Brands/") + filename); lblResult2.Text = "Image " + filename + " successfully uploaded!"; } catch (Exception) { lblResult.Text = "Upload failed!"; } } protected void itemUploadImage1_Click(object sender, AjaxFileUploadEventArgs e) { if (itemType1.Checked) { string filename = e.FileName; Session["PicturePath1"] = filename; itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename); } else if (itemType2.Checked) { string filename = e.FileName; Session["PicturePath1"] = filename; itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Bass/") + filename); } } protected void itemUploadImage2_Click(object sender, AjaxFileUploadEventArgs e) { if (itemType1.Checked) { string filename = e.FileName; Session["PicturePath2"] = filename; itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename); } else if (itemType2.Checked) { string filename = e.FileName; Session["PicturePath2"] = filename; itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Bass/") + filename); } } protected void btnSave_Click(object sender, EventArgs e) { if (brandTypeGuitar.Checked && !brandTypeBass.Checked) { try { string brand_image = ConnectionClassBrands.brandFileName; string brand_name = brandName.Text; ConnectionClassBrands.AddBrandsForOneType(brandTypeGuitar.Text, brand_name, brand_image); lblResult.Text = "Upload successful!"; } catch (Exception) { lblResult.Text = "Upload Failed!"; } } else if (brandTypeBass.Checked && !brandTypeGuitar.Checked) { try { string brand_image = ConnectionClassBrands.brandFileName; string brand_name = brandName.Text; ConnectionClassBrands.AddBrandsForOneType(brandTypeBass.Text, brand_name, brand_image); lblResult.Text = "Upload successful!"; } catch (Exception) { lblResult.Text = "Upload Failed!"; } } else if (brandTypeGuitar.Checked && brandTypeBass.Checked) { try { string brand_image = ConnectionClassBrands.brandFileName; string brand_name = brandName.Text; ConnectionClassBrands.AddBrandsForTwoTypes(brandTypeGuitar.Text, brandTypeBass.Text, brand_name, brand_image); lblResult.Text = "Upload successful!"; } catch (Exception) { lblResult.Text = "Upload Failed!"; } } else { lblResult.Text = "Upload Failed!"; } ClearTextFields(); } protected void Button1_Click(object sender, EventArgs e) { if (itemType1.Checked) { int item_type = ConnectionClassBrands.GetIdByType(itemType1.Text); int item_brandId = ConnectionClassBrands.GetIdByBrand(itemBrand.Text); string item_model = itemModel.Text; double item_price = Convert.ToDouble(itemPrice.Text); string item_image1 = Session["PicturePath1"].ToString(); string item_image2 = Session["PicturePath2"].ToString(); string item_description = itemDescription.Text; string item_necktype = itemNeckType.Text; string item_body = itemBody.Text; string item_fretboard = itemFretboard.Text; string item_fret = itemFret.Text; string item_bridge = itemBridge.Text; string item_neckpickup = itemNeckPickup.Text; string item_bridgepickup = itemBridgePickup.Text; string item_hardwarecolor = itemHardwareColor.Text; ConnectionClassGuitarItems.AddStringInstrumentItems(item_type,item_brandId,item_model,item_price,item_image1,item_image2, item_description,item_necktype,item_body,item_fretboard,item_fret,item_bridge,item_neckpickup, item_bridgepickup,item_hardwarecolor); lblResult2.Text = "Upload successful!" + item_image1 + " and " + item_image2; } else if (itemType2.Checked) { try { int item_type = ConnectionClassBrands.GetIdByType(itemType2.Text); int item_brandId = ConnectionClassBrands.GetIdByBrand(itemBrand.Text); string item_model = itemModel.Text; double item_price = Convert.ToDouble(itemPrice.Text); string item_image1 = Session["PicturePath1"].ToString(); string item_image2 = Session["PicturePath2"].ToString(); string item_description = itemDescription.Text; string item_necktype = itemNeckType.Text; string item_body = itemBody.Text; string item_fretboard = itemFretboard.Text; string item_fret = itemFret.Text; string item_bridge = itemBridge.Text; string item_neckpickup = itemNeckPickup.Text; string item_bridgepickup = itemBridgePickup.Text; string item_hardwarecolor = itemHardwareColor.Text; ConnectionClassGuitarItems.AddStringInstrumentItems(item_type, item_brandId, item_model, item_price, item_image1, item_image2, item_description, item_necktype, item_body, item_fretboard, item_fret, item_bridge, item_neckpickup, item_bridgepickup, item_hardwarecolor); lblResult2.Text = "Upload successful!"; ClearTextFields2(); } catch (Exception ex) { lblResult2.Text = ex.Message; } } } }
Я действительно не понимаю, почему он равен нулю. Я действительно попробовал этот кусок кода в небольшой программе, и все работает нормально. Надеюсь,вы сможете мне помочь.
Вот также трассировка стека ошибки:
Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 159: string item_model = itemModel.Text; Line 160: double item_price = Convert.ToDouble(itemPrice.Text); Line 161: string item_image1 = Session["PicturePath1"].ToString(); Line 162: string item_image2 = Session["PicturePath2"].ToString(); Line 163: string item_description = itemDescription.Text; Source File: c:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\CreateBrands.aspx.cs Line: 161 Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] Pages_CreateBrands.Button1_Click(Object sender, EventArgs e) in c:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\CreateBrands.aspx.cs:161 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler. RaisePostBackEvent(String eventArgument) +12 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639