MVC 表單提交

用戶提交表單程序員

寫法一(推薦)post

一,不帶參數測試

 

 1 <body>  
 2     <!--一下寫法生成:<form action="/Home/Index" method="post"> BeginForm裏不帶參數,就表示請求從哪裏來,表單就提交到哪裏去。  
 3         由於當前視圖是Home控制器下的Index視圖。因此,當請求這個Index視圖的時候,form的action的提交的地址就是/Home/Index  
 4         -->  
 5     @using (Html.BeginForm("Add","Home",new{ id=200}))  
 6     {  
 7         <input type="text" name="userName" />  
 8     }  
 9   
10 </body>

二,帶參數url

1 <body>  
2     <!--一下寫法生成:<form action="/Home/Add/200?pric=25" method="get">  -->  
3     @using (Html.BeginForm("Add","Home",new{ id=200,pric=25},FormMethod.Get))  
4     {  
5         <input type="text" name="userName" />  
6     }  
7   
8 </body> 

三,程序員本身指定一個路由,來生成一個action的URL。使用Html.BeginRouteForm(...)spa

不帶參數:code

1 <body>  
2     <!--由程序員指定一個路由規則,來生成一個action的URL  -->  
3     <!--如下代碼最後生成這樣:<form action="/Index/Home" method="post">  注意:按照Default2這個路由規則來生成的,全部Index在前面-->  
4     @using (Html.BeginRouteForm("Default2"))  
5     {  
6         <input type="text" name="userName" />  
7     }  
8   
9 </body> 

帶參數:orm

1 <body>  
2     <!--由程序員指定一個路由規則,來生成一個action的URL  -->  
3     <!--如下代碼最後生成這樣:<form action="/Index/Home/100" method="post"> 注意:按照Default2這個路由規則來生成的,全部Index在前面-->  
4     @using (Html.BeginRouteForm("Default2",new{controller="Home",action="Index",Id=100},FormMethod.Post))  
5     {  
6         <input type="text" name="userName" />  
7     }  
8   
9 </body> 

下面是路由規則blog

 1 namespace MvcAppEF  
 2 {  
 3     public class RouteConfig  
 4     {  
 5         public static void RegisterRoutes(RouteCollection routes)  
 6         {  
 7             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
 8   
 9             routes.MapRoute(  
10                 name: "Default",  
11                 url: "{controller}/{action}/{id}",  
12                 defaults: new { controller = "Test", action = "Index2", id = UrlParameter.Optional }  
13             );  
14   
15             routes.MapRoute(  
16                 name: "Default2",  
17                 //注意:爲了測試Html.BeginRouteForm,我將{action}這個佔位符與{controller}佔位符換了一下位置。咱們來檢查一下Html.BeginRouteForm最後生成什麼樣的url?  
18                 url: "{action}/{controller}/{id}/{name}",  
19                 defaults: new { controller = "Test", action = "Index2", id = UrlParameter.Optional, name = UrlParameter.Optional }  
20             );  
21         }  
22     }  
23 }  

寫法二(不推薦)路由

不帶參數:get

1 <body>  
2     <!--一下寫法生成:<form action="/Home/Add" method="post">-->  
3     @{Html.BeginForm("Add", "Home");}  
4   
5     <input type="text" name="userName" />  
6   
7     @{Html.EndForm();};  <!--這段代碼最終生成:</form>;-->  
8   
9 </body>  

帶參數:

1 <body>  
2     <!--一下寫法生成:<form action="/Home/Add/100" method="post">-->  
3     @{Html.BeginForm("Add", "Home", new { id=100 },FormMethod.Post);}  
4   
5     <input type="text" name="userName" />  
6   
7     @{Html.EndForm();};  <!--這段代碼最終生成:</form>;-->  
8   
9 </body>  
相關文章
相關標籤/搜索