我的asp.net网站上的ajax代码确实存在问题。 ajax应该做的是通过ajaxfileupload将上传图像的文件名检索到asp.net服务器中。不幸的是结果是,它总是会给我一个Object引用,而不是设置为asp.net代码隐藏中的对象实例,因为它不会从我使用ajaxfileupload上传的图像中返回任何值。然后经过一堆尝试后,它会突然起作用。然后几分钟后,它将无法再次运行。它总是在这个循环中,代码将起作用,然后它将不会,然后它将再次工作。我真的不知道问题是我的ajax代码还是互联网连接。请帮助我们解决这个问题。
这是aspx的代码(我已经包含了我的所有代码,但主要关注的是ajax脚本和具有itemFileUpload1和itemFileUpload2 ID的AjaxFileUpload):
<%@ 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: "Pages/CreateBrands.aspx",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result1) {
OnSuccess1(result1.d);
},
error: function (xhr, status, error) {
OnFailure1(error);
}
});
}
function OnSuccess1(result1) {
var pp1 = document.getElementById("PicturePath1");
pp1.value = result1;
}
function OnFailure1(error) {
alert(error);
}
</script>
<script type="text/javascript">
function uploadComplete2(sender, args) {
var txt = document.getElementById("validatePicture2");//Your
hiddenfield id
txt.value = "1";
$.ajax({
type: "post",
url: "Pages/CreateBrands.aspx",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result2) {
OnSuccess1(result2.d);
},
error: function (xhr, status, error) {
OnFailure1(error);
}
});
}
function OnSuccess1(result2) {
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/BassBrands.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;">
<strong>Brand Type:</strong></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;">
<strong>Brand Name:</strong></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">
<strong>Brand Image:</strong></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;">
<strong>Item Type:</strong></td>
<td style="height: 37px">
<asp:RadioButton ID="itemType1" runat="server"
Text="Guitar" AutoPostBack="False" GroupName="itemType"
OnCheckedChanged="itemType1_CheckedChanged"/>
<asp:RadioButton ID="itemType2" runat="server"
Text="Bass" AutoPostBack="False" GroupName="itemType"
OnCheckedChanged="itemType1_CheckedChanged"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
<strong>Item Brand:</strong></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;">
<strong>Item Model:</strong></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;">
<strong>Item Price:</strong></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;">
<strong>Item Image1:</strong></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;">
<strong>Item Image2:</strong></td>
<td style="height: 37px">
<br />
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server" OnUploadComplete="itemUploadImage2_Click" OnClientUploadComplete="uploadComplete2" MaximumNumberOfFiles="1"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
<strong>Item Description:</strong></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;">
<strong>Item Neck Type:</strong></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;">
<strong>Item Body:</strong></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;">
<strong>Item Fretboard:</strong></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;">
<strong>Item Fret:</strong></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;">
<strong>Item Bridge:</strong></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;">
<strong>Item Neck Pickup:</strong></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;">
<strong>Item Bridge Pickup:</strong></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;">
<strong>Item Hardware Color:</strong></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>
这是代码隐藏(我还包括代码隐藏中的每个代码,但主要焦点仅在于mehtod名称ItemUploadImage1_Click,ItemUploadImage2_Click和Button1_Click。我会在Button1_Click中得到错误,它会总是指出字符串item_image1为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 itemType1_CheckedChanged(object sender, EventArgs e)
{
Session["itemType"] = (sender as RadioButton).Text;
}
protected void itemUploadImage1_Click(object sender, AjaxFileUploadEventArgs
e)
{
if (Session["itemType"] != null) {
if (Session["itemType"].ToString() == "Guitar")
{
string filename = e.FileName;
Session["PicturePath1"] = filename;
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String
Instrument Items/Guitar/") + filename);
}
else if (Session["itemType"].ToString() == "Bass")
{
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 (Session["itemType"] != null) {
if (Session["itemType"].ToString() == "Guitar")
{
string filename = e.FileName;
Session["PicturePath2"] = filename;
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
else if (Session["itemType"].ToString() == "Bass")
{
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 168: string item_model = itemModel.Text;
Line 169: double item_price =
Convert.ToDouble(itemPrice.Text);
Line 170: string item_image1 =
Session["PicturePath1"].ToString();
Line 171: string item_image2 =
Session["PicturePath2"].ToString();
Line 172: string item_description = itemDescription.Text;
Source File: c:\Users\User1\Documents\Visual Studio
2015\WebSites\MusicStore\Pages\CreateBrands.aspx.cs Line: 170
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:170
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
答案 0 :(得分:0)
您的代码中存在一些问题:
1. Ajax Url :
url: "Pages/CreateBrands.aspx" // Worng
Correct Url : "CreateBrands.aspx/Pages"
//Also ensure that Pages method must be there in your CreateBrands.aspx.cs page.
2. You files name is coming null
string filename = e.FileName;
//Check if e.filename is null or not before setting it into the Session Variable.
//If it is null then you can try using normal asp:FileUpload
and through jquery you can make the ajax call with help of fileUpload id.
$('#itemFileUpload1').click(function() {..Your ajax call inside..});
3. Also you are using the
Session["PicturePath1"] //which is fine
//but in your aspx page you are accessing it like
document.getElementById("PicturePath1");
//This is wrong you cannot access Session variable like this .You can
directly use your session variable in aspx page like:
"<%=Session["PicturePath1"]%>".
尝试进行这些更改并检查其是否有效 谢谢!