asp.net開發的對.aspx,.ascx和.ashx都不會陌生。關于它們,網上有很多文章介紹。“紙上得來終覺淺,絕知此事要躬行”,下面自己總結一下做個筆記。
1、.aspx
Web窗體設計頁面。Web窗體頁由兩部分組成:視覺元素(html、服務器控件和靜態文本)和該頁的編程邏輯(VS中的設計視圖和代碼視圖可分別看到它們對應得文件)。VS將這兩個組成部分分別存儲在一個單獨的文件中。視覺元素在.aspx 文件中創建。
2、.ascx
asp.net的用戶控件,是作為一種封裝了特定功能和行為(這兩者要被用在Web應用程序的各種頁面上)的Web頁面被開發的。一個用戶控件包含了html、代碼和其他Web或者用戶控件的組合,并在Web服務器上以自己的文件格式保存,其擴展名是*.ascx。asp.net里的缺省配置并不允許Web客戶端通過url來訪問這些文件,但是這個網站的其他頁面可以集成這些文件里所包含的功能。
3、.ashx
前面兩個都太熟悉了,這個才是要講的重點。
(1)、使用舉例
.ashx文件是主要用來寫web handler的。使用.ashx 可以讓你專注于編程而不用管相關的web技術。我們熟知的.aspx是要做html控件樹解析的,.aspx包含的所有html實際上是一個類,所有的html都是類里面的成員,這個過程在.ashx是不需要的。ashx必須包含IsReusable屬性(這個屬性代表是否可復用,通常為true),而如果要在ashx文件用使用Session必須實現IRequiresSessionState接口.
一個簡單的實現修改登錄用戶密碼的示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
namespace Test
{
public class HandlerTest : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ClearContent();
context.Response.ContentType = "text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache); //無緩存
string action = context.Request.Params["action"]; //外部請求
if (action == "modifyPwd") //用戶改密碼
{
string oldPwd = context.Request.Params["pwd"];
//在ashx文件用使用Session必須實現IRequiresSessionState接口
//Session["LogedUser"]是登錄用戶的會話,用戶名和密碼都是test
if (oldPwd.ToUpper() != ((context.Session["LogedUser"]) as Customer).Password.ToUpper()) //用戶輸入的舊密碼和當前登錄用戶的不相同
{
context.Response.Write("舊密碼輸入錯誤!");
}
else
{
context.Response.Write("舊密碼輸入正確!");
}
}
context.Response.End();
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
客戶端的調用(js和頁面部分):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ASHXTest.aspx.cs" Inherits="ASHXTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>mytest</title>
<script type="text/javascript">
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
function createXMLHTTP() {
var xmlHttp = false;
var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for (var i = 0; i < arrSignatures.length; i++) {
try {
xmlHttp = new ActiveXObject(arrSignatures[i]);
return xmlHttp;
}
catch (oError) {
xmlHttp = false; //ignore
}
}
// throw new Error("MSXML is not installed on your system.");
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
// 發送ajax處理請求(這里簡單驗證舊密碼的有效性)
function validateOldPwd(oTxt) {
var url = "/HandlerTest.ashx?action=modifyPwd&pwd=" + escape(oTxt.value); //.ashx文件
xmlReq.open("get", url, true);
xmlReq.setRequestHeader("If-Modified-Since", "0");
xmlReq.onreadystatechange = callBack;
xmlReq.send(url); // 發送文本
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
alert(xmlReq.responseText); // 接收文本
}
else if (xmlReq.status == 404) {
alert("Requested URL is not found.");
} else if (xmlReq.status == 403) {
alert("Access denied.");
} else
alert("status is " + xmlReq.status);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="txtOldPwd" type="text" onblur="validateOldPwd(this)" />
</div>
</form>
</body>
</html>
分析:
a、以前我們通常都是通過一個簡單的aspx文件實現的功能,其實通過ashx也可以。
筆者曾經寫過的一篇ajax:數據傳輸方式簡介 ,通過對比,我們發現aspx要將前后臺顯示和處理邏輯分開,所以就弄成了兩個文件,其實,在最終編譯的時候,aspx和cs還是會編譯到同一個類中去.這中間就要設計html的一些邏輯處理;而ashx不同,它只是簡單的對web http請求的直接返回你想要返回的結果.比aspx少處理了html的過程(但是ashx也可以處理html的一些邏輯,只是通常都不這么用)。理論上ashx比aspx要快。
b、還是在相同的舊文里,我們知道數據傳輸的幾種方式,其實ashx都可以實現(修改ashx文件里context.Response.ContentType 即可),這里不再贅述了。
(2)、ashx特別適合于生成動態圖片,生成動態文本(純文本,json,xml,javascript等即可)等。
(3)、.ashx文件有個缺點:它處理控件的回發事件非常麻煩。處理數據的回發,通常都需要一些.aspx頁的功能,只有自己手動處理這些功能(還不如直接建一個aspx文件來處理)。所以,一般使用.ashx輸出一些不需要回發處理的項目即可。
4、總結
aspx-->P(Page)
ascx-->C(Control)
ashx-->H(HttpHandler)
當瀏覽器訪問web服務器,我們最終接收到的還是html文本。瀏覽器通過渲染引擎解釋這些標簽,在屏幕上展現出可見的效果。而asp.net不過就是我們應用的一種平臺技術來"變相"解釋html的,說白了它就是為了提高生產率,它的技術術語再多,本質上還是html范疇內的東西(如果你不通過那些動態頁面技術完全利用html和瀏覽器(當然包括js)技術來實現動態頁面效果,那么你會發現效果有了代碼量也相當可觀).所以說web開發的底層就是一堆的html標簽,無論是asp.net還是jsp都是對html某種方式的包裝,是html的產物。
一、數據庫設計
二、Model實體類
public class banqi_attach
{
public int id { get; set; }
public string bqid { get; set; }
public string file_name { get; set; }
public string file_path { get; set; }
public int file_size { get; set; }
public DateTime create_time { get; set; }
public DateTime update_time { get; set; }
}
三、DAL數據訪問層:注意涉及增加和根據id獲取列表用于顯示
//增加數據
public int Add(Model.banqi_attach model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into banqi_attach(");
strSql.Append("[bqid],[file_name] ,[file_path] ,[file_size],[create_time] )");
strSql.Append(" values (");
strSql.Append("@bqid,@file_name,@file_path,@file_size,@create_time)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = {
new SqlParameter("@bqid", SqlDbType.NVarChar,20),
new SqlParameter("@file_name", SqlDbType.NVarChar,50),
new SqlParameter("@file_path", SqlDbType.NVarChar,100),
new SqlParameter("@file_size", SqlDbType.Int),
new SqlParameter("@create_time", SqlDbType.DateTime)
};
parameters[0].Value = model.bqid;
parameters[1].Value = model.file_name;
parameters[2].Value = model.file_path;
parameters[3].Value = model.file_size;
parameters[4].Value = model.create_time;
//添加主表數據
object obj = new SqlHelper().ExecuteScalar(strSql.ToString(), parameters, CommandType.Text);
model.id = Convert.ToInt32(obj);
return model.id;
}
//根據bqid 顯示附件列表
public DataTable GetList(string bqid)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from banqi_attach where bqid='"+bqid+"'");
return new SqlHelper().ExecuteQuery(strSql.ToString(), CommandType.Text);
}
四、前臺頁面:包含一些對上傳文件基本屬性的驗證,如類型、大小等
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="banqi_attach.aspx.cs" Inherits="Peixun.Web.banqi_attach" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>班期附件</title>
<style type="text/css">
*{margin:0;padding:0;}
a{text-decoration:none;}
ul.imglist{ margin:0 auto; overflow:hidden;}
ul.imglist li{list-style:none; float:left; padding:14px 8px; width:280px; margin-bottom:20px; }
ul.imglist li img{ display:block; width:280px; height:200px}
ul.imglist li span{ display:block;width:100%; height:30px; line-height:30px; background:#F6F6F6;text-align:center;text-decoration: none;}
.part{ margin:0 auto; width:1200px;}
</style>
<link rel="stylesheet" href="./css/xadmin.css">
<script src="https://libs.baidu.com/jquery/1.3.2/jquery.min.js" type="text/javascript"> </script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>
</head>
<body>
<div class="part">
<form id="form1" runat="server">
附件名稱:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<div class="layui-upload">
<asp:FileUpload ID="FileUpload" runat="server" />
<input type="button" value="上傳圖片 " class="layui-btn layui-btn-danger" onclick="ajaxFileUpload()"/>
<br /><br />
<div style="border: 1px solid blue;">
<img alt="" class="layui-upload-img" id="demo1" style=" width:300px; height:200px;">
<asp:Label ID="demoText" runat="server"></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
</div>
</div>
<asp:Button ID="btnSubmit" runat="server" Text="確定上傳" CssClass="layui-btn" onclick="btnSubmit_Click" />
</div>
<!--圖片列表-->
<asp:Repeater ID="rptList2" runat="server">
<HeaderTemplate>
<div class="part">
<h3>附件列表</h3>
<ul class="imglist">
</HeaderTemplate>
<ItemTemplate>
<li>
<a href="<%#Eval("file_path")%>" target="_blank">
<img src=<%#Eval("file_path")%> />
<span><%#Eval("file_name")%><br /><%#Eval("create_time")%></span>
</a>
</li>
</ItemTemplate>
<FooterTemplate>
<%#rptList2.Items.Count == 0 ? "<div align=\"center\" style=\"font-size:12px;line-height:30px;color:#666;\">暫無記錄</div>" : ""%>
</ul>
</div>
</FooterTemplate>
</asp:Repeater>
<!--/圖片列表-->
</div>
</form>
<script type="text/javascript">
function ajaxFileUpload() {
var filePath = $("#FileUpload").val();
if (filePath == "") {
alert("請選擇文件");
}
var size = $("#FileUpload")[0].files[0].size; //獲取文件大小,單位字節B
alert(size);
var type = filePath.substr(filePath.indexOf(".")); //獲取擴展名,格式如.jpg
if (type == ".jpg" || type == ".gif" || type == ".JPG" || type == ".GIF") {
alert("符合要求格式");
}
else {
alert("格式錯誤");
}
$.ajaxFileUpload(
{
url: 'ajaxupload.ashx', //需要鏈接到服務器地址
secureuri: false,
fileElementId: 'FileUpload', //文件選擇框的id屬性
dataType: 'json', //服務器返回的格式,可以是json
success: function (data, status) //相當于java中try語句塊的用法
{
$("#demo1").attr("src", "../upload/" + data.savefilename + "");
$("#demoText").html(data.msg);
$("#HiddenField1").val("/upload/" + data.savefilename);
$("#HiddenField2").val(data.filesize);
},
error: function (data, status, e) //相當于java中catch語句塊的用法
{
alert(data.error);
}
}
);
}
</script>
</body>
</html>
五、異步處理ashx文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Peixun.Web
{
/// <summary>
/// ajaxupload 的摘要說明
/// </summary>
public class ajaxupload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string msg = string.Empty;
string error = string.Empty;
string result = string.Empty;
HttpPostedFile _upfile = context.Request.Files["FileUpload"];
string savepath = HttpContext.Current.Server.MapPath("~") + "\\upload\\";
int file_size = _upfile.ContentLength; //獲取上傳文件大小
//判斷上傳文件夾是否存在,若不存在,則創建
if (!System.IO.Directory.Exists(savepath))
{
System.IO.Directory.CreateDirectory(savepath); //創建文件夾
}
if (_upfile.FileName != "")
{
//string savefilename = System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + _upfile.FileName;//聲稱文件名,以時間命名防止重復
string savefilename = System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + _upfile.FileName.Substring(_upfile.FileName.IndexOf(".")).ToLower(); //注意Substring和IndexOf的寫法中的大小寫,獲取擴展名并小寫。
_upfile.SaveAs(savepath + savefilename);
msg = "文件上傳成功!";
result = "{msg:'" + msg + "',savefilename:'" + savefilename + "',filesize:'"+file_size.ToString()+"'}";
}
else
{
error = "文件上傳失敗!";
result = "{ error:'" + error + "'}";
}
context.Response.Write(result);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
六、頁面后臺代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Peixun.Web
{
public partial class banqi_attach : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DAL.banqi_attach().GetList( Request.QueryString["bqid"]);
rptList2.DataSource = dt;
rptList2.DataBind();
}
#region 增加操作=================================
private bool DoAdd()
{
bool result = false;
Model.banqi_attach model = new Model.banqi_attach();
model.file_name = TextBox1.Text.Trim();
model.file_path = HiddenField1.Value;
model.create_time = DateTime.Now;
model.bqid = Request.QueryString["bqid"];
model.file_size =Convert.ToInt32(HiddenField2.Value);
if (new DAL.banqi_attach().Add(model) > 0)
{
result = true;
}
return result;
}
#endregion
//保存
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!DoAdd())
{
Response.Write("<script>alert('錯誤!');</script>");
return;
}
else
{
Response.Write("<script>alert('上傳成功!');var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index); parent.location.reload(); </script>");
}
}
}
}
七、效果圖
、源碼描述
1、前端:EasyUI、JQuery請求處理流程:html界面發起ajax請求 -> 調用ashx -> 調用存儲過程(或SQL) -> 返回Json -> html界面
二、功能介紹
用于維護系統常用的基礎數據,增量不大、或者變更不頻繁的數據都可以維護在這里。如:
1、訂單類型:生產、試制、DUMMY等
2、返工原因:來料不良、制程不良、人為操作、設備原因等
3、點檢項目:外觀、溫度、濕度等
1、后臺表介紹:
基礎數據包含兩張表:基礎數據頭表、和行表。頭表用來保存基礎數據類別,字段包含:基礎數據類別、類別描述、是否系統參數、創建人、創建日期、更新人和更新日期行表用來保存具體的基礎數據,字段包含:參數值、參數描述、擴展字段、創建人、創建日期、更新人和更新日期
2.、操作介紹:
步驟一:打開“基礎數據維護”界面,先維護“基礎數據類別”
步驟二:選中步驟一維護的類別,點擊“查看參數行”按鈕,來維護該類別的具體基礎數據
步驟三:修改、刪除
三、注意事項
1、開發環境為Visual Studio 2015,數據庫為SQLServer2008,使用.net 4.0開發。
MES,制造執行系統,生產管理系統,企業網站|行業軟件|企業應用,Asp.net源碼|- 51Aspx.com
http://www.51aspx.com/code/codename/64900
*請認真填寫需求信息,我們會在24小時內與您取得聯系。