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"]; //集合传参要以 键值对的方式 获得数据
}