顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2020年1月7日 星期二

RedictToActioin 傳參數到另一個 Action 的方式

TempData 來傳

範例:

XXController.cs

public ActionResult action1 () {
 TempData["message"] = "test123";
 return RedirectToAction("action2");
}

public ActionResult action2 () {
  return View();
}

action2 View(Razor)

<script>
alert(@TempData["message"]);
</script>

2014年12月29日 星期一

ASP.NET C# 下載 DataTable 轉 XML


using System.Xml;
using System.Web;
轉換一般的XML

public XmlDocument transDataTableToXMLDocument(DataTable dt)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");

    XmlNode rootNode = xmlDoc.CreateElement("Data");
    if (dt != null &amp;&amp; dt.Rows != null &amp;&amp; dt.Rows.Count &gt; 0)
    {
        foreach (DataRow dr in dt.Rows)
        {
            XmlNode RowNode = xmlDoc.CreateElement("Row");
            foreach (DataColumn dc in dt.Columns)
            {
                XmlNode ColumnNode = xmlDoc.CreateElement(dc.ColumnName);
                ColumnNode.InnerText = dr[dc.ColumnName].ToString();
                RowNode.AppendChild(ColumnNode);
            }
            rootNode.AppendChild(RowNode);
        }
    }
    xmlDoc.AppendChild(rootNode);

    return xmlDoc;
}
轉換 Excel 格式的 XML

public XmlDocument transDataTableToXMLDocument_ExcelFormat(List<DataTable> dts, List<string> tabNames)
{
    if(!(dts != null && tabNames != null && dts.Count == tabNames.Count)){
        throw new Exception("Number of datatable and tabname are not the same.");
    }
    XmlDocument xmlDoc = new XmlDocument();
    string EXCEL_NS = "urn:schemas-microsoft-com:office:spreadsheet";

    xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
    xmlDoc.CreateProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

    // create a Workbook and setting excel format
    XmlNode WorkbookNode = xmlDoc.CreateElement("Workbook", EXCEL_NS);
    XmlAttribute WorkbookNode_xmlns_ss = xmlDoc.CreateAttribute("xmlns", "ss", "http://www.w3.org/2000/xmlns/");
    WorkbookNode_xmlns_ss.Value = EXCEL_NS;
    WorkbookNode.Attributes.Append(WorkbookNode_xmlns_ss);


    // create Sytles
    XmlNode StylesNode = xmlDoc.CreateElement("Styles", EXCEL_NS);

    // create HeaderStyle
    XmlNode HeaderStyleNode = xmlDoc.CreateElement("Style", EXCEL_NS);
    XmlAttribute HeaderStyleNode_ss_ID = xmlDoc.CreateAttribute("ss", "ID", EXCEL_NS);
    HeaderStyleNode_ss_ID.Value = "HeaderStyle";
    HeaderStyleNode.Attributes.Append(HeaderStyleNode_ss_ID);

    XmlNode AlignmentNode = xmlDoc.CreateElement("Alignment", EXCEL_NS);
    XmlAttribute AlignmentNode_ss_Horizontal = xmlDoc.CreateAttribute("ss", "Horizontal", EXCEL_NS);
    XmlAttribute AlignmentNode_ss_Vertical = xmlDoc.CreateAttribute("ss", "Vertical", EXCEL_NS);
    AlignmentNode_ss_Horizontal.Value = "Center";
    AlignmentNode_ss_Vertical.Value = "Center";
    AlignmentNode.Attributes.Append(AlignmentNode_ss_Horizontal);
    AlignmentNode.Attributes.Append(AlignmentNode_ss_Vertical);
    HeaderStyleNode.AppendChild(AlignmentNode);

    XmlNode FontNode = xmlDoc.CreateElement("Font", EXCEL_NS);
    XmlAttribute FontNode_ss_Bold = xmlDoc.CreateAttribute("ss", "Bold", EXCEL_NS);
    FontNode_ss_Bold.Value = "1";
    FontNode.Attributes.Append(FontNode_ss_Bold);
    HeaderStyleNode.AppendChild(FontNode);

    StylesNode.AppendChild(HeaderStyleNode);

    // create TextStyle
    XmlNode TextStyleNode = xmlDoc.CreateElement("Style", EXCEL_NS);
    XmlAttribute TextStyleNode_ss_ID = xmlDoc.CreateAttribute("ss", "ID", EXCEL_NS);
    TextStyleNode_ss_ID.Value = "TextStyle";
    TextStyleNode.Attributes.Append(TextStyleNode_ss_ID);

    XmlNode TextAlignmentNode = xmlDoc.CreateElement("Alignment", EXCEL_NS);
    XmlAttribute TextAlignmentNode_ss_WrapText = xmlDoc.CreateAttribute("ss", "WrapText", EXCEL_NS);
    TextAlignmentNode_ss_WrapText.Value = "1";
    TextAlignmentNode.Attributes.Append(TextAlignmentNode_ss_WrapText);
    TextStyleNode.AppendChild(TextAlignmentNode);

    StylesNode.AppendChild(TextStyleNode);
    WorkbookNode.AppendChild(StylesNode);

    if (dts != null && dts.Count > 0)
    {
        for (int i = 0; i < dts.Count; i++)
        {
            DataTable dt = dts[i];

            // create Worksheet

            XmlNode WorksheetNode = xmlDoc.CreateElement("Worksheet", EXCEL_NS);
            XmlAttribute WorksheetNode_ss_Name = xmlDoc.CreateAttribute("ss", "Name", EXCEL_NS);
            WorksheetNode_ss_Name.Value = tabNames[i];
            WorksheetNode.Attributes.Append(WorksheetNode_ss_Name);

            XmlNode TableNode = xmlDoc.CreateElement("Table", EXCEL_NS);

            // create column style
            if (dt != null && dt.Columns != null && dt.Columns.Count > 0)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    XmlNode ColumnNode = xmlDoc.CreateElement("Column", EXCEL_NS);
                    XmlAttribute ColumnNode_ss_Width = xmlDoc.CreateAttribute("ss", "Width", EXCEL_NS);
                    string columnWidth = "100";
                    if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
                    {
                        if (dc.DataType == System.Type.GetType("System.Decimal"))
                        {
                            IEnumerable<decimal> tmp = dt.AsEnumerable().Where(p => p.Field<decimal?>(dc.ColumnName).HasValue)
                                                                .Select(p => p.Field<decimal?>(dc.ColumnName).Value);
                            if (tmp != null && tmp.Count() > 0)
                            {
                                columnWidth = (tmp.Select(p => Convert.ToString(p).Length).Max() * 8).ToString();
                            }
                        }
                        else if (dc.DataType == System.Type.GetType("System.String"))
                        {
                            IEnumerable<string> tmp = dt.AsEnumerable().Where(p => p.Field<string>(dc.ColumnName) != null)
                                                                .Select(p => p.Field<string>(dc.ColumnName));
                            if (tmp != null && tmp.Count() > 0)
                            {
                                columnWidth = (tmp.Select(p => p.Length).Max() * 8).ToString();
                            }
                        }
                        else if (dc.DataType == System.Type.GetType("System.DateTime"))
                        {
                            columnWidth = "160";
                        }
                    }
                    if (((dc.ColumnName.Length) * 8) > Convert.ToInt16(columnWidth))
                    {
                        columnWidth = (dc.ColumnName.Length * 8).ToString();
                    }
                    if (Convert.ToInt16(columnWidth) > 200)
                    {
                        columnWidth = "200";
                    }
                    ColumnNode_ss_Width.Value = columnWidth;
                    ColumnNode.Attributes.Append(ColumnNode_ss_Width);
                    TableNode.AppendChild(ColumnNode);
                }
            }

            // create row header

            XmlNode RowHeaderNode = xmlDoc.CreateElement("Row", EXCEL_NS);
            XmlAttribute RowHeaderNode_ss_StyleID = xmlDoc.CreateAttribute("ss", "StyleID", EXCEL_NS);
            RowHeaderNode_ss_StyleID.Value = "HeaderStyle";
            RowHeaderNode.Attributes.Append(RowHeaderNode_ss_StyleID);

            if (dt != null && dt.Columns != null && dt.Columns.Count > 0)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    XmlNode CellNode = xmlDoc.CreateElement("Cell", EXCEL_NS);

                    XmlNode DataNode = xmlDoc.CreateElement("Data", EXCEL_NS);
                    XmlAttribute DataNode_ss_Type = xmlDoc.CreateAttribute("ss", "Type", EXCEL_NS);
                    DataNode_ss_Type.Value = "String";
                    DataNode.Attributes.Append(DataNode_ss_Type);
                    DataNode.InnerText = dc.ColumnName;
                    CellNode.AppendChild(DataNode);

                    RowHeaderNode.AppendChild(CellNode);
                }
            }

            TableNode.AppendChild(RowHeaderNode);

            // create row data

            if (dt != null && dt.Rows != null && dt.Rows.Count > 0 && dt.Columns != null && dt.Columns.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    XmlNode RowNode = xmlDoc.CreateElement("Row", EXCEL_NS);

                    XmlAttribute RowNode_ss_StyleID = xmlDoc.CreateAttribute("ss", "StyleID", EXCEL_NS);
                    RowNode_ss_StyleID.Value = "TextStyle";
                    RowNode.Attributes.Append(RowNode_ss_StyleID);

                    foreach (DataColumn dc in dt.Columns)
                    {
                        XmlNode CellNode = xmlDoc.CreateElement("Cell", EXCEL_NS);

                        XmlNode DataNode = xmlDoc.CreateElement("Data", EXCEL_NS);
                        XmlAttribute DataNode_ss_Type = xmlDoc.CreateAttribute("ss", "Type", EXCEL_NS);
                        DataNode_ss_Type.Value = "String";
                        DataNode.Attributes.Append(DataNode_ss_Type);
                        DataNode.InnerText = dr[dc.ColumnName].ToString();
                        CellNode.AppendChild(DataNode);

                        RowNode.AppendChild(CellNode);
                    }

                    TableNode.AppendChild(RowNode);
                }
            }

            WorksheetNode.AppendChild(TableNode);

            WorkbookNode.AppendChild(WorksheetNode);
        }
    }

    xmlDoc.AppendChild(WorkbookNode);

    return xmlDoc;
}
下載XML

public void downloadDataTableToXMLFile(List<DataTable> dts, List<string> tabNames, string fileName)
{
    CommonService cs = new CommonService();
    XmlDocument doc = cs.transDataTableToXMLDocument_ExcelFormat(dts, tabNames);

    MemoryStream ms = new MemoryStream();
    using (XmlWriter writer = XmlWriter.Create(ms))
    {
        doc.WriteTo(writer); // Write to memorystream
    }

    byte[] data = ms.ToArray();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.Expires = 0;
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.AddHeader("Content-Disposition",
                        "attachment;filename=" + HttpUtility.UrlEncode(fileName) + ";size=" + data.Length.ToString());
    HttpContext.Current.Response.ContentType = "Application/octet-stream";
    HttpContext.Current.Response.BinaryWrite(data);
    HttpContext.Current.Response.End();
    ms.Flush(); // Probably not needed
    ms.Close();
}

ASP.NET C# 在IE和FireFox中下載檔名正常,但在Chrome中下載檔名會變成XXX.aspx

若原來的只有輸入 attachment 和 filename

HttpContext.Current.Response.AddHeader("Content-Disposition:", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
再加入size變成

HttpContext.Current.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(fileName) + ";size=" + data.Length.ToString());

2013年12月8日 星期日

轉 : .Net Framework 讀取檔案變亂碼的處理方式

http://www.neo.com.tw/archives/243

今天因為做長榮的案子,壓根沒想到 Microsoft .Net Framework 讀取檔案竟然會出現亂碼,以前用 VB 都鮮少遇過這種事。
20040710_01.gif

重點還是在於如何解決,因為從 Windows 2000 之後的作業系統在檔案處理採用Unicode ,所以 .Net 的檔案處理也是預設為 Unicode ,但是文字檔大多還是以 ANSI 儲存,而且裡面的編碼還是用 Big5,所以才會造成中文亂碼的狀況,也就是在讀取檔案的時候就要指定編碼的樣式。
本來會造成亂碼的語法如下:
Dim reader As StreamReader =
New StreamReader(FileName)
但是問題來了,System.Text.Encoding 裡面一堆,ASCII、UTF-8 等等的,要選哪個好?
其實很簡單,用 System.Text.Encoding.Default 告訴 StreamReader 目前作業系統的編碼即可。
[VB .Net] 的寫法
Dim reader As StreamReader = _
New StreamReader(FileName, System.Text.Encoding.Default)
[C# .Net] 的寫法
StreamReader reader = _
New StreamReader(FileName, System.Text.Encoding.Default)
結果如下:
20040710_02.gif

2013年11月19日 星期二

轉 : 利用Byte單位來計算字串長度的幾種做法(Javascript,C#,VB.Net)

http://www.dotblogs.com.tw/puma/archive/2008/08/05/4815.aspx

一般計算字串長度,有下列幾種:
1.計算字元數,不管中文字,英文字都算一個字元
2.計算Byte數,中文字算2個byte,英文字算1個byte
舉例:
字串為:"我是puma"
1.計算字元數:中文字(2),英文字(4),總共(6)
2.計算Byte數:中文字(4),英文字(4),總共(8)
程式語法
C#
string str = "我是puma";

//一般的字中長度計算,中文字(2),英文字(4),總共(6)

Response.Write(str.Length.ToString());

//利用Byte單位來計算字串長度,中文字(4),英文字(4),總共(8)

Response.Write(System.Text.Encoding.Default.GetBytes(str).Length);

VB.Net
Dim str As String = "我是puma"

'一般的字中長度計算,中文字(2),英文字(4),總共(6)
Response.Write(str.Length.ToString())

'利用Byte單位來計算字串長度,中文字(4),英文字(4),總共(8)
Response.Write(System.Text.Encoding.Default.GetBytes(str).Length)

Javascript(小舖Bryan(不來ㄣ)提供)
<script type="text/javascript"> 
//string.Blength() 傳回字串的byte長度 
String.prototype.Blength = function() { 
var arr = this.match(/[^\x00-\xff]/ig); 
return  arr == null ? this.length : this.length + arr.length; 


var str = "我是puma"; 
alert("字元數:"+str.length); //中文字(2),英文字(4),總共(6)
alert("byte數:"+str.Blength()); //中文字(4),英文字(4),總共(8)
</script>

2012年10月8日 星期一

.NET MVC 中文檔案下載

因為每一個版本的狀況不同 ...

目前這樣測試都可以成功的把中文檔案下載下來..

string targetPath = Server.MapPath("/filesrc/") + File_Name;
string tmp_filename = File_Name;
 if (Request.Browser.Browser == "IE"|| Request.Browser.Browser == "Opera")
{
       tmp_filename = Server.UrlPathEncode(tmp_filename);
}else if (Request.Browser.Browser == "Safari" ){
       string strContentDisposition = String.Format("{0}; filename=\"{1}\"", "attachment", tmp_filename);
       Response.AddHeader("Content-Disposition", strContentDisposition);
}
 return File(targetPath, File_ContentType, tmp_filename);

瀏灠器測試版本
IE 9 及其各種相容性檢示
Chrome 22.0.1229.79 m
Firefox 15.0.1
Opera 12.02
Safari 5.1.7(7534.57.2)