標籤:io os 使用 ar for sp on cti log
構件Form表單
1.Html.BeginForm()
該方法用於構建一個From表單的開始,他的構造方法為:
Html.BeginForm("ActionName","ControllerName",FormMethod.method)
一般構建一個表單結構如下
<% using(Html.BeginForm ("index","home",FormMethod.Post)){ %>
。。。。。。
<%} %>
他將在用戶端產生一個類似<form action="/account/login" method="post"></form>標籤
2.現在開始建立一個表單一實例,首先在Index.aspx中構建一個表單
<% using(Html.BeginForm ("index","home",FormMethod.Post)){ %>
帳號:<%=Html .TextBox ("username") %>
<br/>
密碼:<%=Html .Password ("password") %>
<br />
<input type="submit" value="登入" />
<%} %>
3.在對應得控制器HomeController.cs中寫入下面代碼,傳遞出一個ViewData[]字典:
public ActionResult Index()
{
string struser = Request.Form["username"];
string strpass = Request.Form["password"];
ViewData["w"] = "你的帳號是:" + struser + "你的密碼是:" + strpass;
return View();
}
4.在Index.aspx中寫接受傳值
<%=ViewData ["w"] %>
ViewData做一下解釋
1.ViewData[]字典:
1.簡單的傳值
a.首先我們在控制器HomeController.cs中建立一個ViewData[]字典:
public ActionResult Index()
{
ViewData["strValue"] = "這是一個傳遞的值";//這裡是我們傳遞的ViewData[]
return View();
}
b.然後我們就可以在相對應得Index.aspx中寫上:
<%: ViewData["strValue"] %>
控制器向視圖中傳值ViewData詳解
1.將一個字串傳值到視圖中
在action中我們將字串儲存在ViewData(或ViewBag [asp.net 3或以上才可用])中代碼如下:
public ActionResult Index()
{
ViewData["str1"]= "這是一個字串";
//也可以使用ViewBag來傳遞值
ViewBag.str2="這是另外一個字串";
return View();
}
在視圖中我們可以用下面代碼將字串顯示出來
<h1>@ViewData["str1"]</h1>
<h1>@ViewBag.str2</h1>
2.將一個字串集合傳遞到視圖中
public ActionResult Index()
{
List<string> str1= new List<string>();
str1.Add("1111");
str1.Add("2222");
str1.Add("3333");
ViewData["str"] = str1;
return View();
}
在視圖中我們通過下面語句將str1的值顯示出來
@foreach (var a in ViewData["str"] as List<string>)
{
@a
}
3.將一個datatable的值傳遞到視圖中
public ActionResult Index()
{
DataTable newtable = new DataTable("d");
newtable.Columns.Add("商品編號", typeof(string));
newtable.Columns.Add("客戶編碼", typeof(string));
DataRow NewRow = newtable.NewRow();
NewRow["商品編號"] = "132323213434";
NewRow["客戶編碼"] = "344223443244";
newtable.Rows.Add(NewRow);
DataRow SNewRow = newtable.NewRow();
SNewRow["商品編號"] = "343432445456";
SNewRow["客戶編碼"] = "454523432453";
newtable.Rows.Add(SNewRow);
ViewData["dt"]= newtable;
return View();
}
在視圖中我們通過下面語句將dt的值顯示出來
注意:在頂部要先加上:@using System.Data;
<ul>
@foreach(DataRow dr in (ViewData["dt"] as DataTable).Rows)
{
<li>
@dr["商品編號"],@dr["客戶編碼"],
</li>
}
</ul>
MVC筆記一表單應用