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"]; //集合传参要以 键值对的方式 获得数据
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构