3月 31, 2014

MVC 檔案上傳fileupload

Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try

            
            Dim a2 As FileUpload = FormView1.FindControl("FileUpload2")
            a2.SaveAs(Server.MapPath("./upload/") + a2.FileName)

            Dim c2 As Label = FormView1.FindControl("Label444")
            c2.Text = a2.FileName
            a2.Enabled = False

            Dim d2 As Button = FormView1.FindControl("Button4")
            d2.Enabled = False
            Label2.Text = "上傳成功!!"
        Catch ex As Exception
            Label2.Text = ex.ToString()
        End Try
    End Sub
首先在VIEW中輸入程式碼:
<form action="@Url.Action("MultiUpload")" method="post" enctype="multipart/form-data">
    <input id="File1" type="file" name="files"/>
    <input id="File2" type="file" name="files"/>
    <input id="Submit1" type="submit" value="submit" />
    <input id="Reset2" type="reset" value="reset" />
</form>
接著是controll中的files必須對應到input的tag中的name即可
[HttpPost]
        public ActionResult MultiUpload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    
                    var path = Server.MapPath("~/App_Data/") + file.FileName;
                    file.SaveAs(path);
                }
            }
            return RedirectToAction("Index");
            
        }

3月 30, 2014

MVC Jquery傳checkbox已勾選的物件陣列回control

首先在View中加入webgrid並且放入checkbox
<div id="gridContent">
@grid.GetHtml(
columns: grid.Columns(
grid.Column("id", "id", format: @<input class="select" id="assignChkBx" name="assignChkBx" type="checkbox" value="@item.id"/>),
grid.Column("item", "item"),
grid.Column("name", "改字", style: "description")
)) 
</div>

Jquery的寫法如下
$("#Button2").click(function () {
            var str=[];
            $("input:[name='assignChkBx'][checked]").each(function () {      
                str.push($(this).val());
            });
            $.post("@Url.Content("~/store/bgg")",
                   
                    {user:JSON.stringify(str)  },
                    function (res) {
                        alert(res);
                    });
        });

接著回到controll
由於物件陣列的回傳會因為jquery的處理而接收不到
因此必須在controll底下加入一個處理方法
 /// <summary>
    /// FromJsonAttribute
    /// 用在透過javascript 傳送json格式資料到controller時使用
    /// </summary>
    public class FromJsonAttribute : CustomModelBinderAttribute
    {
        /// <summary>
        /// JavaScriptSerializer
        /// </summary>
        private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();

        /// <summary>
        /// GetBinder
        /// </summary>
        /// <returns>Binder</returns>
        public override IModelBinder GetBinder()
        {
            return new JsonModelBinder();
        }

        /// <summary>
        /// JsonModelBinder
        /// </summary>
        private class JsonModelBinder : IModelBinder
        {
            /// <summary>
            /// BindModel
            /// </summary>
            ///<param name="controllerContext">controllerContext
            ///<param name="bindingContext">bindingContext
            /// <returns>object</returns>
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
                if (string.IsNullOrEmpty(stringified))
                {
                    return null;
                }

                return serializer.Deserialize(stringified, bindingContext.ModelType);
            }
        }
    }


然後接著是controll的部分
string tt;
        public ActionResult bgg([FromJson]List<int> user)
        {
            
            
            if (user != null)
            {
                foreach(var item in user){
                    tt += item.ToString();
                }
            }
                return Content(tt);
            
        }

如此一來就能將被勾選的Value正確傳給controll~!

3月 29, 2014

MVC sds dr da大全

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
//--------------------------------
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
/// <summary>
/// WebService 的摘要描述
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下列一行。
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //如果使用設計的元件,請取消註解下列一行
        //InitializeComponent(); 
    }

    [WebMethod]
    public DataTable HelloWorld() {
        string sc = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(sc);
        cn.Open();
        string sql = "select * from city";
        SqlCommand cmd = new SqlCommand(sql, cn);
        SqlDataAdapter da = new SqlDataAdapter(sql, cn);
        DataSet ds = new DataSet();
        da.SelectCommand = cmd;
        da.Fill(ds);
        ds.Dispose();
        da.Dispose();
        cmd.Dispose();
        cn.Close();
        cn.Dispose();
        return ds.Tables[0];
    }
    [WebMethod]
    public string[] city(int city)
    {
        string sc = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(sc);
        cn.Open();
        string sql = "select * from city where id=@id";
        SqlCommand cmd = new SqlCommand(sql, cn);
        cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = city;
        SqlDataReader dr = cmd.ExecuteReader();
        string[] dt = new string[2];
        while (dr.Read())
        {
            dt[0] = dr[0].ToString();
            dt[1] = dr[1].ToString();
        }
        cmd.Dispose();
        cn.Close();
        cn.Dispose();
        return dt;
    }
    [WebMethod]
    public DataTable[] hi()
    {
        string sc = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(sc);
        cn.Open();
        string sql = "select * from area;select * from city";
        SqlCommand cmd = new SqlCommand(sql,cn);
        SqlDataAdapter da = new SqlDataAdapter(sql, cn);
        DataTable[] dt = new DataTable[] {new DataTable("dt1"),new DataTable("dt2")};
        da.SelectCommand = cmd;
        da.Fill(0,0,dt);
        da.Dispose();
        cmd.Dispose();
        cn.Close();
        cn.Dispose();
        return dt;
    }
    [WebMethod]
    public DataTable hida(int id)
    {
        string sc = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(sc);
        cn.Open();
        string sql = "select * from city where id=@id";
        SqlCommand cmd = new SqlCommand(sql, cn);
        cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
        SqlDataAdapter da = new SqlDataAdapter(sql, cn);
        DataTable dt = new DataTable();
        da.SelectCommand = cmd;
        da.Fill(dt);
        da.Dispose();
        cmd.Dispose();
        cn.Close();
        cn.Dispose();
        return dt;
    }
    [WebMethod]
    public SqlDataSource sds(string id)
    {
        SqlDataSource sds = new SqlDataSource();
        sds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        sds.SelectCommand = "select * from city where id=@id";
        sds.SelectParameters.Add(new Parameter("id", System.Data.DbType.Int32, id));
        //sds.Select(DataSourceSelectArguments.Empty);
        return sds;
    }
    [WebMethod]
    public int clear(int id)
    {
        string sc = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(sc);
        cn.Open();
        SqlTransaction tran = cn.BeginTransaction();
        string sql = "update item set lp=20 where id=@id";
        SqlCommand cmd = new SqlCommand(sql, cn , tran);
        cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
        string sql2 = "update item set lp=20 where id=2";
        SqlCommand cmd2 = new SqlCommand(sql2,cn,tran);
        try
        {
            cmd.ExecuteNonQuery();
            cmd2.ExecuteNonQuery();
            tran.Commit();
        }
        catch (Exception e)
        {
            tran.Rollback();
        }
        cmd.Dispose();
        cn.Close();
        cn.Dispose();
        return 0;
    }
    [WebMethod]
    public int inse(string id,string aid,string area)
    {
        SqlDataSource sds = new SqlDataSource();
        sds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        sds.InsertCommand = "insert into area(id,aid,area)values(@id,@aid,@area)";
        sds.InsertParameters.Add(new Parameter("id", System.Data.DbType.Int32, id));
        sds.InsertParameters.Add(new Parameter("aid", System.Data.DbType.Int32, aid));
        sds.InsertParameters.Add(new Parameter("area", System.Data.DbType.String, area));
        sds.Insert();
        return 0;
    }
    [WebMethod]
    public DataTable Hdd()
    {
        string sc = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(sc);
        cn.Open();
        string sql = "select * from city";
        SqlCommand cmd = new SqlCommand(sql, cn);
        SqlDataAdapter da = new SqlDataAdapter(sql, cn);
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataTable dt = new DataTable();
        da.SelectCommand = cmd;
        da.Fill(dt);
        da.InsertCommand = cb.GetInsertCommand();
        da.InsertCommand.Connection = cn;
        
        da.UpdateCommand = cb.GetUpdateCommand();
        da.UpdateCommand.Connection = cn;

        da.DeleteCommand = cb.GetDeleteCommand();
        da.DeleteCommand.Connection = cn;

        //修改
        DataRow dr1 = dt.Rows[0];
        dr1[1] = "台北市";
        //新增
        //DataRow dr2 = dt.NewRow();
        //dr2[0] = 5;
        //dr2[1] = "嘉義市";
        //dt.Rows.Add(dr2);

        //刪除
        //dt.Rows[4].Delete();
        //DataRow dr3 = dt.Rows[4];
        //dr3.Delete();
        //dt.Rows.RemoveAt(4); 不顯示但是不刪除
        //foreach (DataRow dr in dt.Select("ID='101'"))
        //{
        //    //dr.Delete();
        //}
        da.Update(dt);
        da.Dispose();
        cmd.Dispose();
        cn.Close();
        cn.Dispose();
        return dt;
    }
    
}

3月 28, 2014

在GridView做加減並更新

 protected void gv_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < gv.Rows.Count; i++)
        {
            Label aa = (Label)gv.Rows[i].Cells[6].FindControl("Label3");
            
            if (aa != null)
            {
                if (aa.Text.Trim().StartsWith("-")) aa.Text = "0";
                int number;
                string hu = aa.Text.Trim();
                int.TryParse(hu, out number);
                int num2 = int.Parse(DropDownList1.SelectedValue);
                int num3 = number * num2;
                gv.Rows[i].Cells[7].Text = num3.ToString();
            }
            
        }


    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlDataSource ses = new SqlDataSource();
        ses.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["immis"].ConnectionString;
        ses.UpdateCommand = "update hi set total=@total where id=101";
        ses.UpdateParameters.Add(new Parameter("total", TypeCode.String));
        ses.UpdateParameters["total"].DefaultValue = DropDownList1.SelectedValue.ToString();
        ses.Update();

    }

3月 27, 2014

MVC 進階WebGrid的用法

首先在VIEW前面宣告如下
@using mvc3.Models;
@{
    ViewBag.Title = "index";
    Model aa = new Model();
    var grid = new WebGrid(aa.gridv(), canPage: true, rowsPerPage: 15,
selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
}
接著是在需要呈現的HTML如下
<div id="gridContent">
@grid.GetHtml(
columns: grid.Columns(
grid.Column("id", "id"),
grid.Column("item", "item"),
grid.Column("name", "改字", style: "description")
)) 
</div>
在MODEL的程式碼如下
public class data
        {
            public string id { get; set; }
            public string item { get; set; }
            public string name { get; set; }
        }
        public List<data> gridv()
        {
            string a = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            SqlConnection conn = new SqlConnection(a);
            conn.Open();
            string sql = "select [id],[item],[cs] from item";
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader dr = cmd.ExecuteReader();
            List<data> oop = new List<data>();
            while(dr.Read())
            {            
                oop.Add(new data()
                {
                    id = dr[0].ToString(),
                    item = dr[1].ToString(),
                    name = dr[2].ToString()
                });
            }
            dr.Close();
            dr.Dispose();
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
            return oop;
        }
不用WebGrid的方法如下
@foreach (var d in aa.gridv()){
      <table>
          <tr><td>@d.id</td><td>@d.item</td><td>@d.name</td></tr>
     </table>
}

3月 24, 2014

MVC 高階連動式下拉選單DropDownList

首先在View新增兩個下拉選單
@Html.DropDownList("select2",null ,new { id="Select2"})
@Html.DropDownList("select3",null ,new { id="Select3"})
根據上一篇的結果 我們會在Controll中把縣市的資料塞給Select2

        Model ty = new Model();  
        public ActionResult Index()
        {
            
            ViewBag.select2 = ty.see();
            ViewBag.select3 = ty.see3("3");
            return View();
        }
然後因為Select2有預設選項為3 所以我們在ty.see3(3)就給3 然後進Model開始寫see3()的方法如下
public List<SelectListItem> see3(string city)
        {
            string a = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            SqlConnection conn = new SqlConnection(a);
            conn.Open();
            string sql = "select area , aid from area where id=@id";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = city;
            SqlDataAdapter da = new SqlDataAdapter(sql,conn);
            DataTable dt = new DataTable();
            da.SelectCommand = cmd;
            da.Fill(dt);
            List<SelectListItem> yuii = new List<SelectListItem>();
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                yuii.Add(new SelectListItem()
                {
                    Text = dt.Rows[i].ItemArray[0].ToString(),
                    Value = dt.Rows[i].ItemArray[1].ToString()
                    
                });
            }
            da.Dispose();
            dt.Dispose();
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
            return yuii;
        }
接著回到Controll另外寫個ActionResult:
public ActionResult details(string user)
        {
            
            var sop = ty.see3(user);
            TagBuilder tb = new TagBuilder("select");
            tb.GenerateId("Select3");
            tb.MergeAttribute("name","select3");
            foreach (var item in sop)
            {
                tb.InnerHtml+="<option value='"+item.Value.ToString()+"'>"+item.Text.ToString()+"</option>";
                         
            }
            return Content(tb.ToString());
            
        }
這邊是等AJAX呼叫時馬上去跟MODEL要資料再生成HTML程式碼return回去 記得ID要一樣,然後接著是前端的Jquery寫法如下
$("#Select2").change(function () {/*當縣市的下拉選單改變時*/
                var selected = $("#Select2 option:selected");
                $.post("@Url.Content("~/home/details")",
                        { user: selected.val() },
                        function (res) {
                            $("#Select3").replaceWith(res);
                            
                        });
                
            });
如此一來,當縣市的選單改變後,會post選取值去Controll那邊 然後controll那邊會負責要資料在return出HTML,選區域的Select3的選項就會改變!

3月 23, 2014

MVC 進階ListBox和DropDownList

首先要到Model.cs記得using System.Web.Mvc;
public List<SelectListItem> see()
        {
            string a = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            SqlConnection conn =new SqlConnection(a);
            conn.Open();
            string sql = "spii";
            SqlCommand cmd = new SqlCommand(sql,conn);
            
            SqlDataReader dr = cmd.ExecuteReader();
            List<SelectListItem> yui = new List<SelectListItem>();
            
            
                for (int i = 0; i <=dr.FieldCount+1; i++)
                {
                    dr.Read();
                    yui.Add(new SelectListItem()
                    {
                        Text = dr[1].ToString(),
                        Value = dr[0].ToString(),
                        Selected = dr[0].Equals(3)
                    });
                }
            
            
            dr.Close();
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
            return yui;
            
        }

接著利用List將資料return
回到Controll那邊:
Model ty = new Model();
public ActionResult Index()
{
    ViewBag.select1 = ty.see();
    ViewBag.select2 = ty.see();
}

再回到View:
@Html.ListBox("select1", null, new { id="SelectList2",size="2"})
@Html.DropDownList("select2",null ,new { id="Select2"})
大功告成!!

3月 22, 2014

MVC 淺談ListBox和DropDownList

純靜態ListBox No Value:
<select id="SelectList1" multiple="multiple" name="uu" size="2">
        <option>hello</option>
        <option selected>apple</option>
        <option>listbox</option>
        <option>All</option>
    </select>
    @Html.ListBox("select1", null, new { id="SelectList2",size="2"})
塞值方法如下:
進該頁的Controll:
public ActionResult Index()
        {
            
            string[] yy = new string[2];
            yy[0] = "1";
            yy[1] = "2";
            
            SelectList LB = new SelectList(yy);
            ViewBag.select1 = LB;
            

            return View();
        }

純靜態DropDownList No Value:

    <select id="Select1">
        <option>dog</option>
        <option>cat</option>
    </select>
    @Html.DropDownList("select2",null ,new { id="Select2"})

塞值方法如下:
進該頁的Controll:
public ActionResult Index()
        {
            string[] gg = new string[2];
            gg[0] = "HIGH";
            gg[1] = "LOW";
            
            SelectList DDL = new SelectList(gg);
            ViewBag.select2 = DDL;
            
           

            return View();
        }

3月 21, 2014

MVC 比較特別要注意的用法

<label for="CheckBox1">CheckBox1</label><br>
@Html.Label("CheckBox1")
<br>
<a href="/" id="link1" target="_Blank">thisislink</a><br>
@Html.ActionLink("thisislink","index" , null, new { id="link1",target="_Blank"})
<br>
<a href="@Url.Content("http://google.tw")" target="_blank"><img alt="" src="logo_s.gif" /></a>
<br>
就只是按鈕:<input id="Button1" type="button" value="button" /><br>
水平線: <hr /><br>

3月 20, 2014

MVC Html對照

 @Html.Label("CheckBox:")<br>
    <input id="Checkbox1" name="group1" type="checkbox" value="yes" checked="checked"/>yes
    @Html.CheckBox("group1",false,new {id="Checkbox2",value="no"})
    <label for="checkbox1">no</label>
    <br>
    @Html.Label("RadioButton:")<br>
    <input id="RadioButton1" name="group2" type="radio" value="man"/>man
    @Html.RadioButton("group2","female", true, new { id="rd1"})female
    <br>
    @Html.Label("Textbox:")<br>
    First name: <input id="textbox1" name="name" type="text" value=""><br>
    Last name:  @Html.TextBox("name", "", new {id="textbox2" })
    <br>
    @Html.Label("Password:")<br>
    Password: <input id="password1" name="pwd" type="password">
    confim Password:@Html.Password("pwd", "", new {id="password2" })
    <br>
    @Html.Label("Hidden:")<br>
    <input id="Hidden1" name="hide" type="hidden" value="text" />
    @Html.Hidden("hide", "text", new { id="Hidden2"})
    <br>
    @Html.Label("TextArea:")<br>
    <textarea cols="20" id="TextArea1" name="TextArea1" rows="2"></textarea>
    @Html.TextArea("TextArea2")
    <br>
輸出結果:
<label for="CheckBox:">CheckBox:</label><br>
    <input id="Checkbox1" name="group1" type="checkbox" value="yes" checked="checked"/>yes
    <input id="Checkbox2" name="group1" type="checkbox" value="no" /><input name="group1" type="hidden" value="false" />
    <label for="checkbox1">no</label>
    <br>
    <label for="RadioButton:">RadioButton:</label><br>
    <input id="RadioButton1" name="group2" type="radio" value="man"/>man
    <input checked="checked" id="rd1" name="group2" type="radio" value="female" />female
    <br>
    <label for="Textbox:">Textbox:</label><br>
    First name: <input id="textbox1" name="name" type="text" value=""><br>
    Last name:  <input id="textbox2" name="name" type="text" value="" />
    <br>
    <label for="Password:">Password:</label><br>
    Password: <input id="password1" name="pwd" type="password">
    confim Password:<input id="password2" name="pwd" type="password" value="" />
    <br>
    <label for="Hidden:">Hidden:</label><br>
    <input id="Hidden1" name="hide" type="hidden" value="text" />
    <input id="Hidden2" name="hide" type="hidden" value="text" />
    <br>
    <label for="TextArea:">TextArea:</label><br>
    <textarea cols="20" id="TextArea1" name="TextArea1" rows="2"></textarea>
    <textarea cols="20" id="TextArea2" name="TextArea2" rows="2">
</textarea>
    <br>
而RadioButton的屬性name要一樣才能只選其中之一

3月 19, 2014

純javascript

function aa(){
document.getElementById("ff12").innerHTML = document.getElementById("aa1").value;
document.getElementById("ff9").innerHTML = document.getElementById("aa4").value;
document.getElementById("ff4").innerHTML = document.getElementById("aa9").value;
document.getElementById("ff1").innerHTML = document.getElementById("aa12").value;
document.getElementById("ff11").innerHTML = document.getElementById("aa2").value;
document.getElementById("ff10").innerHTML = document.getElementById("aa3").value;
document.getElementById("ff2").innerHTML = document.getElementById("aa11").value;
document.getElementById("ff3").innerHTML = document.getElementById("aa10").value;
document.getElementById("ff5").innerHTML = document.getElementById("aa8").value;
document.getElementById("ff6").innerHTML = document.getElementById("aa7").value;
document.getElementById("ff7").innerHTML = document.getElementById("aa6").value;
document.getElementById("ff8").innerHTML = document.getElementById("aa5").value;
}

3月 12, 2014

開新視窗

 protected void btn_Click(object sender, EventArgs e)
    {
        string newWin =

        "window.open('pub.aspx');";

        ClientScript.RegisterStartupScript

            (this.GetType(), "pop", newWin, true);
        
    }

3月 08, 2014

MVC

View:
<script>
    $(document).ready(function () {
        
        $("#s1").click(function () {
            var selected = $("#do1 option:selected");
            $.post("@Url.Content("~/store/bgg")",
                    {user:selected.val()},
                    function (res) {
                        alert(res);
                    });
            
        });
        //$("#do1").click
    })
</script>
<h2>indexstore</h2>
<select id="do1">
    <option>dog</option>
    <option>pig</option>
</select>
<input id="s1" type="submit" value="submit" />
controll加入:
public ActionResult bgg(string user)
{
            
    return  Content(string.Format("已傳送訊息給{0}",user));
}