用户提交表单
写法一(推荐)
一,不带参数
<body>
<!--一下写法生成:<form action="/Home/Index" method="post"> BeginForm里不带参数,就表示请求从哪里来,表单就提交到哪里去。
因为当前视图是Home控制器下的Index视图。所以,当请求这个Index视图的时候,form的action的提交的地址就是/Home/Index
-->
@using (Html.BeginForm("Add","Home",new{ id=200}))
{
<input type="text" name="userName" />
}
</body>
二,带参数
<body>
<!--一下写法生成:<form action="/Home/Add/200?pric=25" method="get"> -->
@using (Html.BeginForm("Add","Home",new{ id=200,pric=25},FormMethod.Get))
{
<input type="text" name="userName" />
}
</body>
三,程序员自己指定一个路由,来生成一个action的URL。使用Html.BeginRouteForm(...)
带参数:
<body>
<!--由程序员指定一个路由规则,来生成一个action的URL -->
<!--以下代码最后生成这样:<form action="/Index/Home/100" method="post"> 注意:按照Default2这个路由规则来生成的,所有Index在前面-->
@using (Html.BeginRouteForm("Default2",new{controller="Home",action="Index",Id=100},FormMethod.Post))
{
<input type="text" name="userName" />
}
</body>
不带参数
<body>
<!--由程序员指定一个路由规则,来生成一个action的URL -->
<!--以下代码最后生成这样:<form action="/Index/Home" method="post"> 注意:按照Default2这个路由规则来生成的,所有Index在前面-->
@using (Html.BeginRouteForm("Default2"))
{
<input type="text" name="userName" />
}
</body>
下面是路由规则
namespace MvcAppEF
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Test", action = "Index2", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default2",
//注意:为了测试Html.BeginRouteForm,我将{action}这个占位符与{controller}占位符换了一下位置。我们来检查一下Html.BeginRouteForm最后生成什么样的url?
url: "{action}/{controller}/{id}/{name}",
defaults: new { controller = "Test", action = "Index2", id = UrlParameter.Optional, name = UrlParameter.Optional }
);
}
}
}
写法二(不推荐)
<body>
<!--一下写法生成:<form action="/Home/Add" method="post">-->
@{Html.BeginForm("Add", "Home");}
<input type="text" name="userName" />
@{Html.EndForm();}; <!--这段代码最终生成:</form>;-->
</body>
还可以带参数:
<body>
<!--一下写法生成:<form action="/Home/Add/100" method="post">-->
@{Html.BeginForm("Add", "Home", new { id=100 },FormMethod.Post);}
<input type="text" name="userName" />
@{Html.EndForm();}; <!--这段代码最终生成:</form>;-->
</body>