Because if the path in the view page is directly written dead to <from action= "/home/save" method= "POST" > Then when the routing in the Global.asax.cs file is customized or modified at any time, the window send path in dozens of views is also modified.
In MVC, we can use the Html.BeginForm ()
ASPX code
- <%
- using (Html.BeginForm ("Save", "Home", FormMethod.Post)) {
- %>
- Window contents
- <%}%>
Or
ASPX code
- <%
- using (Html.BeginForm ("Save", "Home")) {
- %>
- Window contents
- <%}%>
If the object being sent by the window is the same action, it can be shortened to
ASPX code
- <%
- using (Html.BeginForm ()) {
- %>
- Window contents
- <%}%>
Because the object that is sent out is the same as the controller in which the current view is located, only the action is different, so you can get all the current route values through the view's Routedata.values object and dynamically load the name of the controller in the route value
Routedata.values
ASPX code
- <%
- using (Html.BeginForm ("Save", routedata.values["Controller"). ToString ())) {
- %>
- Window contents
- <%}%>
Use <%: Html.textbox ("name")%> to mvc2 new strongly typed Html helper method
The advantage of using a strong type is that you can be prompted without worrying about writing the field name incorrectly
Model to be heavy, controller to light, view to be stupid enough
HTML helper methods:
MVC's built-in and commonly used HTML helper methods are divided into two main categories:
The HTML helper method used to generate the hyperlink, HTML. ActionLink (), HTML. RouteLink ();
An HTML helper method for generating window elements, including Html.BeginForm (), HTML. Endfrom (), HTML. TextBox (), HTML. TextArea (), HTML. Password (), HTML. Hidden (), HTML. CheckBox (), HTML. DropDownList (), HTML. ListBox (), HTML. RadioButton ();
Html. ActionLink ():
ASPX code
- <%=html. ActionLink ("hyperlink text", "ActionName")%>
- <%=html. ActionLink ("hyperlink text", "ActionName", "Controllername")%>
- <%=html. ActionLink ("hyperlink text", "ActionName", "Controllername", new{id=123,page=5})%>
When using HTML. ActionLink (), the hyperlink text is not allowed to enter a blank or "null" value, otherwise it will throw "the value cannot be null or Emtty" exception.
Html. RouteLink ():
ASPX code
- <%=html. RouteLink ("member area", "Member", new{type= "Default"},new{@class = "Back"})%>
- Equivalent:
- <a class= "Back" href= "Member/?type=default" > member Area </a>
Html. BeginForm ():
This method is primarily used to generate <form> tags, which you can use using syntax, or with the Html.endform () helper method to produce the appropriate </from> window end tags. Note that the use of this is <%%> must not be equated.
Html. TextBox ():
<%=html. TextBox ("name")%> equivalent to <input id= "name" name= "name" type= "text" value= ""/> So we have specified the Name field, The HTML helper method produces the HTML code at the same time that the ID field is assigned the same value as the Name field.
<%=html. TextBox ("name", "value")%> equivalent to <input id= "name" name= "name" type= "text" value= "value"/> Note that the value here cannot be written ""
<%=html. TextBox ("name", "Value", new{id= "TestID"})%> equivalent to <input id= "TestID" name= "name" type= "text" value= " Value "/> is worth noting that the HTML attribute class is reserved word, when the need to set the class is, need to add" @ "to jump off
<%=html. TextBox ("name", "Value", new{id= "TestID", @class = "TestClass"})%>
You can also use the Idictionary<stirng object> interface, which is used when there are many HTML tags in the same page that need to use the same class or style attributes. Using this overload requires that a Dictionary object be created in the controller now, and using ViewData to go to the view
C # code
- Public ActionResult Helpersample () {
- idictionary<string,object> attr = new dictionary<string,object> ();
- attr. ADD ("Siez", "32");
- attr. ADD ("Style", "color:red");
- viewdata["Dictionary"]=ATTR;
- return View ();
- }
<%=html. TextBox ("name", "Value", viewdata["Dictionary"] as idictionary<string,object>)%>
<%=html.httpmethodoverride ("Httpverbs.delete")%> used to be MVC support rest protocol.
Strongly-typed helper methods are named after the last name with "for"
URL helper Methods:
URL-assisted methods are similar to HTML-assisted methods, which are used to generate HTML code and HTML-assisted methods for generating URLs;
Url.action ():
ASPX code
- <%=url.action ("about")%>
- <%=url.action ("About", new{id=1})%>
- <%=url.action ("About", "Home")%>
- <%=url.action ("About", "Home", new{id=1})%>
Url.encode ():
Same as the use of the Server.rrlencode () method.
Url.content ():
Can be used to get the absolute path <%=url.content ("~/image/logo.png")%>
Url.routeurl ():
You can specify that a route name be used to generate a URL
Url.route (new{id=123})/home/index/123
Url.route ("root")/root/home/index
Url.route ("Root", new{id=123})/root/home/index/123
Url.route ("Root", new{id=123}, "https") https://localhost/root/Home/Index/123
Ajax Helper Methods:
When using the Ajax helper method, the two JS files of MicrosoftAjax.js and microsoftmvaajax.js must be loaded in the page or masterpage, and the order of loading should be correct, otherwise it will be an error.
The most commonly used auxiliary methods are:
Ajax.actionlink ()
Ajax.beginform ()
And the two auxiliary methods and Html.ActionLink (), html.beginform are roughly the same, just one more ajaxoptions class can be set
ajaxoptions Property name |
say Ming |
Confim |
Comfirm dialog box pops up when clicked |
HttpMethod |
How to set the HTTP request (GET or POST) |
Insertionmode |
When retrieving data through an Ajax helper method, there are 3 ways to create a new data to the element specified by the Updatetargetid property: Insertionmode.replace: Override the content specified by the Updatetargetid property Insertionmode.insertbefore: Insert before Updatetargetid property Insertionmode.insertafter: Inserted after the Updatetargetid property |
Loadingelementid |
Blocks displayed when reading is not yet complete |
Onbegin |
Sets the name of the JavaScript function to execute at the start |
OnComplete |
The name of the JavaScript function to execute at the end of the setting |
OnFailure |
The JavaScript function name to execute when setting failed |
Onsuccess |
The name of the JavaScript function to execute when the setting is complete |
Updatetargetid |
Set the return value to display on which ID |
Url |
Set the URL of the request |
The following is an Ajax helper method to delete data from the demo:
ASPX code
- <%ajax.actionlink ("delete", "delete", new {controller= "Home", id= "model.id"},new ajaxoptions{onsuccess= "Delete", Confirm= "Are you sure you want to delete it? "},httpmethod=" POST ", loadingelementid=" Ajaxload ")%>
- <script language= "javascript" type= "Text/javascript" >
- function Delete (data) {
- alert (data.get_data);
- }
- </script>
In the action
C # code
- [HttpPost]
- Public ActionResult Delete (string id) {
- ....
- Return content ("delete succeeded");
- }
Custom HTML helper methods:
C # code
- Using System;
- Using System.Text;
- Using SYSTEM.WEB.MVC;
- Namespace Mvcapplication1.helpers
- {
- public static Class Imghelper
- {
- public static string Img (this htmlhelper helper,string url,string alternatetext,string title) {
- Return String.Format ("
- }
- }
- }
Note that because we use a custom HTML helper method, you must refer to the namespace at the top of the view to use this custom HTML helper method, as shown in the following example:
<%@ Import namespace= "Mvcapplication1.helper"%>
<%=html.img ....
If you write complex helper classes, you need to stitch strings, use StringBuilder, but this class uses no elasticity, so MVC has designed the Tagbuilder class to generate HTML tags in a much more object-like way.
Verify:
You can use MVC built-in data validation mechanism, as long as with the ViewModel and ASP. NET 5 SP1, or asp.net4.0 provide the data annotations function library, you can achieve the validation of the client and the server side.
Just load the System.ComponentModel.DataAnnotations class in the ViewModel and
[Required (errormessage = "The current password cannot be empty!")]
[DataType (Datatype.password)]
[DisplayName ("Current password")]
Public Stringoldpassword {get; set;}
Background:
With modelstate.isvalid validation, we can determine whether the data that is bound through the database model conforms to the requirements of the ViewModel field validation and returns False if the validation fails
Front desk:
1. Add three project built-in JavaScript files to the Site.master file
<scriptsrc= "Http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type= "Text/javascript" ></script>
<scriptsrc= "Http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type= "Text/javascript" ></script>
<scriptsrc= "Http://www.cnblogs.com/Scripts/MicrosoftMvcValidation.js" type= "Text/javascript" ></script >
2. Add the following declaration before the <% using (Html.BeginForm ()) {%> statement:
<%html.enableclientvalidation (); %>
Note that a: if there are two or more than two windows in a page that need to be validated, html.enableclientvalidation () must appear before the Html.BeginForm () declaration, otherwise the validation cannot be performed ; B: Using this method of authentication must use the Html.BeginForm () Declaration window.
3. Add <%: html.validationmessagefor (model = model) on each field. Name, "", new{Style = "color:red"})%>
To display error hints for validation failures
To send a message repeatedly:
To solve this phenomenon, you can use the concept of the PRG (Post-redirect-get) style, when encountering the need to transfer the window data, will be sent through the HTTP Post request data, after processing the data, immediately turn to (Redirect) another URL, Finally get the page after the jump via HTTP GET request
Public ActionResult About (ViewModel model) {
。。。
Return Redirecttoaction ("Other", "Home");
}
If we want to pass on the ViewModel data to the other view, then we must use the TempData mechanism to pass this data that only uses "1 times".
TempData is a Dictionary object, it and viewdata very much, but very special, all the data stored in the TempData can only be referenced once, after the use of data will be emptied, we can take advantage of the tempdata features, Pass data from the ViewMode class received by the about action to other.
In the About method, you need to have
tempdata["Lastpostviewmodel"]=model;
And then in the other
if (tempdata["Lastpostviewmodel"]==null) {
Return redirecttoaction ("Index");
}
var model = (strong turn) tempdata["Lastpostviewmodel"];
The MVC View section describes