MVC HtmlHelper用法(一)@Html.BeginForm的使用總結


1.@using(Html.BeginForm()){}                                                      //提交到當前頁面

2.@using(Html.BeginForm( new {} )){}                                         //提交到當前頁面,new中可以帶參數

3.@using(Html.BeginForm("action","controller")){}                          //提交到指定controller下

4.@using(Html.BeginForm("action","controller",FormMethod.Post))    //指定提交方式

注:所有要提交的內容包括按鈕都必須在{ }內

example:

1.指定表單提交路徑和方式:

@using(Html.BeginForm("Index","Home",FormMethod.Get,new{ name = "nbForm",id="idForm"})){}

 

html格式:

<form name="nbForm" id="idForm" action="/Home/Index" method="get">  </form>

 

2.指定表單提交方式為文件方式:

@using(Html.BeginForm("ImportExcel","Home",FormMehod.Post,new { enctype="multipart/form-data"})){}

 

html格式:略

注意, 有時候要加{id=1}不然在點擊超過第一頁的索引時form后面會自動加上當前頁的索引,如果此時再搜索則可能會出來“超出索引值”的錯誤提示
@using (Html.BeginForm("Index", null, new { id = 1 }, FormMethod.Get))

 

3.添加new { area = string.Empty }是為了防止提交鏈接后面自帶參數,方式自定,如可寫成 new { id = ""} 

 @using (Html.BeginForm("Shipping", "Order", new { area = string.Empty }, FormMethod.Post, new { id = "ShippingForm" }))

 

4.@using(Html.BeginForm("Index","Home",FormMehod.method)){}也可以寫作

<% using(Html.BeginForm("Index","Home",FormMethod.method)){%>

<%}%>

FormMethod為枚舉方式

public enum FormMethod

{

       Get=0,

       Post=1,      

}

 

5.控制器接受參數的方式

ex:在aspx中

@using(Html.BeginForm("Index","Home",FormMehod.Post))

{

    @Html.TextBox("username")

    @Html.TextBox("password")

    <input type="submit" value="登陸"/>

}

控制器中

public ActionResult Index()

{

   string struser=Request.Form["username"];

   string strpass=Request.From["password"];

   ViewData["v"]="你的賬號是"+struser+"密碼是"+strpass;

   return View();

}

在Index.aspx中接受傳值

<%=ViewData["v"]%>

 

ex:在MVC中

@using (Html.BeginForm("Shipping", "Order", new { area = string.Empty }, FormMethod.Post, new { id = "ShippingForm" }))

{

@Html.ValidationMessage("ShipInfo.DeliverType")
@Html.HiddenFor(m => m.ShipInfo.DeliverCountry)
@Html.HiddenFor(m => m.ShipInfo.DeliverProvince)
@Html.HiddenFor(m => m.ShipInfo.DeliverCity)
@Html.HiddenFor(m => m.ShipInfo.DeliverCityArea)

}

1. HTML標簽name 和參數名一樣

public ActionResult Shipping(string ShipInfo.DeliverType,string ShipInfo.DeliverCountry,string ShipInfo.DeliverProvince,string ShipInfo.DeliverCity,string ShipInfo.DeliverCityArea){}

 

2.HTML標簽name 屬性和Model屬性保持一致

public ActionResult Shipping(Models.ViewModels.Order.OrderViewModel model){}

 

3.表單集合傳參

 public ActionResult Shipping( FormCollection fc)

{

     string strResult=fc["selectOption"];   //集合傳參要以 鍵值對的方式 獲得數據

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM