MVC |表单提交 Html.BeginForm

用户提交表单

写法一(推荐)

一,不带参数

<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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值