ASP.NET ViewState

xiaoxiao2021-03-06  65

When talking to the developer who just contacted the ASP.NET page, they usually give me the first question is: "What is the viewstate?" The feeling of their tone, just like I came to a foreign country. The feelings of the waiter, the feeling of the waiter, I have never seen any dishes - I don't understand, but also curious. But there is certain that someone thinks it is good, otherwise it will not provide. So, I will try it first, may like it, although it looks really quirky!

This is also true for ViewState, but if you adapt to its style, you will find that in many cases, you will be happy to use ViewState in your own ASP.NET application, because it can help you use less code to do more jobs. However, sometimes it is completely abandoned for ViewState. Below we will elaborate on both cases, but let us answer what is ViewState.

Answer: ViewState is not status of the UI status Web for maintenance page, and the ASP.NET page is not status, which is instantiated, executed, rendered, and processed during each round-trip process of the server. As a web developer, you can use well-known technologies (such as stored on the server in a session state, or return the page back to itself). Below we are discussed as an example in Figure 1.

Figure 1: Restore the flexible form value

As can be seen from the figure, I chose an invalid value for the lunch meal. This form is as friendly as most forms on the Web, which displays a useful error message next to the error field and an asterisk. Moreover, all values ​​I have entered in other text boxes and drop-down lists are also shown. This is somewhat possible because the HTML form element sends its current value from the browser to the server in the HTTP header. You can use ASP.NET trackers to view the return form value, as shown in Figure 2.

Figure 2: Retrieved value in the HTTP form (display via ASP.NET tracking)

Before ASP.NET, the value is restored to the value of the value to the Form field through multiple times, they will have to pick up the return value from the HTTP form, and then push it back in the field. Fortunately, now ASP.NET can automatically complete this task, so that the developer eliminates an annoying job, but also does not need to write a lot of code for the form. But this is not ViewState.

ViewState is a mechanism, ASP.NET uses this mechanism to track server control status values, otherwise these values ​​will not be sent back as part of the HTTP form. For example, the text displayed by the Label control is saved in ViewState by default. As a developer, you can bind the data, or only set up the Label programming when loading this page. In subsequent return, the label text will automatically refill from ViewState. Therefore, in addition to cumbersome work and code, ViewState can also reduce the number of round trips of the database.

ViewState's working principle ViewState does not have any mystery, which is a hidden form field managed by the ASP.NET page framework. When ASP.NET performs a page, the viewState value and all controls on this page will be collected and formatted into an encoded string, and then assigned to the value attribute of the hidden form field (ie ) . Since the hidden form field is part of the page sent to the client, the ViewState value is temporarily stored in the client's browser. If the client selects the page back to the server, the ViewState string will also be passed back. The viewState form field and its return value can be seen in Figure 2 above. After passing, the ASP.NET page frame will parse the ViewState string and populate the ViewState property for the page and each control. The control then uses ViewState data to restore yourself to the previous state.

About ViewState has three small problems worth noting.

If you want to use ViewState, you must have a server-side form tag (

) in the ASPX page. The form field is required so that the hidden field containing ViewState information can pass back to the server. Moreover, the form must also be a server-side form, so that when the page is executed on the server, the ASP.NET page framework can add hidden fields. The page itself saves 20-byte information in ViewState to send the postback data and the ViewState value to the correct control at the time of return. Therefore, even if the page or application is disabled, you can still see a small amount of remaining bytes in ViewState. In the case where the page does not return, the ViewState in the page can be removed by omitting the tag of the server. Let's make full use of ViewStateViewState to provide a magical way to the status of the transmission tracking control, as it does not use server resources, not timeout, and applies to any browser. If you want to write controls, then you must need to know how to maintain the status in the control (English).

The developer can also use ViewState in almost the same way, but sometimes the page will contain a UI status value that is not stored. You can track the values ​​in ViewState, using the programming syntax using the session and the syntax of the cache:

[Visual Basic] 'Save in ViewState ("Sortorder") = "DESC"

'Read Dim Sortorder AS String = CSTR (ViewState ("Sortorder") from ViewState

[C #] // Save in ViewState ["Sortorder"] = "DESC";

/ / Read string sortorder = (string) ViewState ["Sortorder"] from ViewState;

Please see the example below: To display a list of items on the web page, and each user needs different list sort. The list of items is static, so they can bind these pages to the same cache dataset, and the sort order is only a small portion of the user-specific UI state. ViewState is ideal for storing this type of value. code show as below:

[Visual Basic] <% @ Import Namespace = "System.data"%> ViewState / Title> </ head> <body> <form runat = "Server for page UI status values "> <H3> Store non-control status in ViewState </ h3> <p> This example stores the current sort order of a column of static data in ViewState. <br> Click the link in the column header to select the data according to this field. <br> Click the link again to sort in the reverse order. <br> <br> <br> <asp: datagrid id = "DataGrid1" runat = "server" OnSortCommand = "SortGrid" BorderStyle = "None" BorderWidth = "1px" BorderColor = "# CCCCCC" BackColor = "White" CellPadding = "5" allowsorting = "true"> <headerstyle font-bold = "true" forcolor = "white" backcolor = "# 006699> </ headerstyle> </ asp: datagrid> </ p> </ form> < / body> </ html> <script runat = "server"> 'Tracking Sortfield Properties in ViewState Property Sortfield () AS String</p> <p>Getdim o as object = viewState ("sortfield") if o is nothing thereturn string.emptyEND ifreturn CSTR (o) End Get</p> <p>Set (Value As String) if Value = Sortfield Ten 'is the same as the current sort file, switching sorting direction sortascending = not sortascendingend IFviewState ("sortfield") = valueend set</p> <p>End Property</p> <p>'Tracking Sortascending Properties in ViewState Property Sortascending () AS Boolean</p> <p>Getdim o as object = viewState ("sortascending") IF o is nothing thereturn truend ifreturn CBOOL (O) End Get</p> <p>Set (Value As Boolean) ViewState ("Sortascending" = ValueEnd Set</p> <p>End Property</p> <p>Private Sub Page_Load (Sender As Object, E AS Eventargs) Handles MyBase.Load</p> <p>IF not page.ispostback thenbindgrid () endiff</p> <p>End Sub</p> <p>Sub bindgrid ()</p> <p>'Get Data DIM DS AS NEW DATASET () DS.Readxml (Server.MAppath ("TestData.xml")) DIM DV AS New DataView (DS.Tables (0))' Apply Sort Filter and Direction DV.Sort = Sortfieldif NOT Sortascending Thendv.Sort = "DESC" end if</p> <p>'Binding Grid DataGrid1.datasource = DVDataGrid1.database ()</p> <p>End Subprivate Sub Sortgrid (Sender As Object, E AS DataGridSortCommandeventArgs) DataGrid1.currentPageIndex = 0Sortfield = E.SortexpressionBindGrid () end sub </ script></p> <p>[C #]% @ page language = "c #"%> <% @ import name "%> <html> <head> <title> for page UI status value for ViewState </ Title> </ Head> <body> <form runat = "server"> <h3> Store non-control status </ h3> <p> in ViewState This example stores the current sort order of a column of static data in ViewState. <br> Click the link in the column header to select the data according to this field. <br> Click the link again to sort in the reverse order. <br> <br> <br> <asp: datagrid id = "DataGrid1" runat = "server" OnSortCommand = "SortGrid" BorderStyle = "None" BorderWidth = "1px" BorderColor = "# CCCCCC" BackColor = "White" CellPadding = "5" allowsorting = "true"> <headerstyle font-bold = "true" forcolor = "white" backcolor = "# 006699> </ headerstyle> </ asp: datagrid> </ p> </ form> < / body> </ html> <script runat = "server"></p> <p>// Track Sortfield attributes in ViewState String Sortfield {</p> <p>Get {Object O = ViewState ["sortfield"]; if (o == null) {return string.empty;} return (string) o;}</p> <p>Set {if (value == sortfield) {// is the same as the current sort file, switch sorting direction sortascending =! sortascending;} ViewState ["sortfield"] = value;}}</p> <p>// Track the Sortascending property bool sortascending {in ViewState</p> <p>Get {Object O = ViewState ["Sortascending"]; if (o == null) {Return True;} Return (BOOL) O;</p> <p>Set {ViewState ["Sortascending"] = value;}}</p> <p>Void Page_Load (Object Sender, Eventargs E) {</p> <p>IF (! page.ispostback) {bindgrid ();}}</p> <p>Void bindgrid () {</p> <p>// Get data dataset ds = new dataset (); ds.readxml (server.mappath ("testdata.xml")); DataView DV = New DataView (DS.Tables [0]);</p> <p>// Applied sort filter and direction DV.Sort = sortfield; if (! Sortascending) {dv.sort = "desc";</p> <p>// Bind grid DataGrid1.datasource = DV; DataGrid1.database ();</p> <p>Void Sortgrid (Object Sender, DataGridSortCommandeventEventArgs E) {</p> <p>DataGrid1.currentpageIndex = 0; sortfield = e.sortexpression; bindgrid ();}</p> <p></ script></p> <p>The following is the code referenced by the TestData.xml referenced in the above two code segments:</p> <p><? XML Version = "1.0" Standalone = "YES"?> <newDataSet> <table> <pub_id> 0736 </ pub_id> <pub_name> new moon books </ pub_name> <city> Boston </ city> <state> Ma </ state> <country> USA </ country> </ table> <table> <pub_id> 0877 </ pub_id> <pub_name> binnet & hardley </ pub_name> <city> Washington </ city> <state> DC </ state> <country> USA </ country> </ table> <table> <pub_id> 1389 </ pub_id> <pub_name> algodata infosystems </ pub_name> <city> Berkeley </ city> <state> CA </ State> <Country> USA </ country> </ table> <table> <pub_id> 1622 </ pub_id> <pub_name> FIVE LAKES PUBLISHING </ PUB_NAME> <City> Chicago </ city> <state> il </ state > <country> USA </ country> </ table> <table> <pub_id> 1756 </ pub_id> <pub_name> Ramona Publishers </ Pub_Name> <City> Dallas </ city> <state> tx </ state> < Country> USA </ country> </ table> <table> <pub_id> 9901 </ pub_id> <pub_name> GGG & g </ pub_name> <city> Muenchen </ city> <country> germany </ country> </ table> <Table> <pub_id> 9952 </ pub_id> <pub_name> scootney books </ pub_name> <city> new york </ city> <state> NY </ state> <country> USA </ country> </ table> < Table> <pub_id> 9999 </ pub_id> <pub_name> lu CERNE PUBLISHING </ PUB_NAME> <city> PARIS </ city> <country> France </ country> </ table> </ newDataSet></p> <p>Select a session status or viewstate? In some cases, save status values ​​in viewState is not the best choice. The most common alternative is a session state, which is usually more suitable for: a large amount of data. Since ViewState adds the size of the page sent to the browser (HTML payload), it also increases the size of the return form, so it is not suitable for storing a large amount of data. Secure data is not displayed in the UI. Although the viewState data has been encoded and can be encrypted, it is the safest to send data to the client. Therefore, the session is a safer option. (Since the database requires additional credentials to verify, the data is stored in the database will be safer. You can add SSL to get a more secure link.) However, if the private data has been displayed in the UI, then you should have confirmed The security of the link. In this case, the same value is placed in ViewState does not reduce security. The objects that have not been serially entered to ViewState, such as DataSet. The ViewState serialization program is optimized for a small part of the commonly used object type, as shown below. Other sequential types may be kept in ViewState, but the speed will slow down and generate a very large viewState. Does the session status ViewState use server resources? Yes Yes? Yes, after 20 minutes (default) No Whether all .NET types are stored? Yes No, only support: string, integer, boolean, array, arraylist, hashtable, and custom TypeConverter add "HTML payload"? no Yes</p> <p>When you get the best performance using ViewState, each object must be serialized into ViewState and then retrore sequencing by backhaul, so it is not cost to use for use. However, if you follow some simple principles to control the cost of ViewState, it usually does not have a significant performance impact.</p> <p>Disable ViewState when you don't need it. The following "Reduce Using ViewState" section will detail this question. Use optimized ViewState serialization procedures. The types listed above have specialized serialization procedures, which are running quickly and have been optimized, which can generate small ViewState. If you want to serialize a type not listed above, you can create a custom TypeConverter to significantly improve its performance. Try to minimize the use object, if possible, minus the number of objects placed in ViewState. For example, do not use a two-dimensional string array (name / value, the number of objects is as much as the length of the array), but should use two string arrays (only two objects). However, before the two known types are stored in ViewState, the conversion between the two will not obtain any performance improvement, as this is actually equivalent to paying the cost of twice. Reduce ViewState will be enabled by default by default, and is determined by each control (not the page developer) to determine the content stored in ViewState. Sometimes this information is not used by the application. Although there is no harm, it will significantly increase the size of the page sent to the browser. So if you don't need to use ViewState, it is best to turn it off, especially when ViewState is large.</p> <p>You can close ViewState based on each control, each page, or each application. In the following cases, you will no longer need the viewState: Page Control Page does not return to itself. Processing is not an event of a control. The control does not have a dynamic or data binding attribute value (or it is set in the code for each request).</p> <p>The DataGrid control is a heavyweight user of ViewState. By default, all data displayed in the grid is also stored in ViewState, which is very useful when a complex operation (such as complex search) is required to obtain data. However, this behavior of DataGrid sometimes makes viewState become cumbersome.</p> <p>For example, there is a simple page that is the above. Because the page does not return to itself, it does not need ViewState.</p> <p>Figure 3: Simple page with DataGrid1 LessViewState.aspx</p> <p><% @ Import namespace = "system.data"%> <html> <body> <form runat = "server"> <ask: DataGrid runat = "server" /> </ form> </ body> </ html> <script runat = "server"></p> <p>Private subject (Sender As Object, E AS Eventargs)</p> <p>DIM DS AS New DataSet () DS.ReadXML (Server.MAppath ("TestData.xml"))</p> <p>DataGrid1.datasource = dsdatagrid1.database ()</p> <p>End Sub</p> <p></ script></p> <p>When ViewState is enabled, this small grid adds more than 3,000-multi-byte HTML payload! Use ASP.NET TRACING (English) or view the source code of the page sent to the browser (as shown in the following code), you can clearly see this.</p> <p><Html> <head> <title> Reduce page "HTML payload" </ title> </ head> <body> <form name = "_ CTL0" method = "post" action = "iD =" _ctl0 "> <input type =" hidden "name =" __ VIEWSTATE "value =" dDwxNTgzOTU2ODA7dDw7bDxpPDE Oz47bDx0PDtsPGk8MT47PjtsPHQ8QDA8cDxwPGw8UGFnZUNvdW50O18hSXRlbUNvdW50O18hRGF0YVNvdXJjZUl0ZW1Db3VudDtEYXRhS2V5czs O2w8aTwxPjtpPDg O2k8OD47bDw Oz4 Oz47bDxpPDA Oz47bDx0PDtsPGk8MT47a TwyPjtpPDM O2k8ND47aTw1PjtpPDY O2k8Nz47aTw4Pjs O2w8dDw7bD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xwPGw8VGV4dDs O2w8Jm5ic3BcOzs Pjs Ozs O3Q8cDxwPGw8VGV4dDs O2w8RnJhbmNlOz4 Oz47Oz47Pj47Pj47Pj47Pj47Pj47Pg == "/> Look! Just disable the Grid's ViewState, the payload of the same page is greatly reduced:</p> <p><Html> <head> <title> Reduce page "HTML payload" </ title> </ head> <body> <form name = "_ CTL0" method = "post" action = "iD =" _ctl0> <input type = "hidden" name = "__ viewstate" value = "ddwxntgzotu2oda7oz4 =" /></p> <p>Here is the complete LessViewState code of Visual Basic and C #:</p> <p>[Visual Basic] <% @ import name "=" system.data "%> <html> <head> <title> Reduce page" HTML payload "</ title> </ head> <body> <form runat =" Server "> <h3> Reduce the" HTML payload "</ h3> <p> <asp: DataGrid id =" DataGrid1 "runat =" limited "borderwidth =" none "borderwidth =" false "borderwidth = "1px" bordercolor = "# ccccc" backcolor = "white" cellpadding = "5"> <headerstyle font-bold = "true" forcolor = "White" backcolor = "# 0066699> </ headerstyle> </ asp: DataGrid> </ p> </ form> </ body> </ html> <script runat = "server"></p> <p>Private subject (Sender As Object, E AS Eventargs)</p> <p>DIM DS As New DataSet () DS.Readxml (Server.Mappath ("TestData.xml")) DataGrid1.datasource = DSDataGrid1.Database</p> <p>End Sub</p> <p></ script></p> <p>[C #]% @ page language = "c #"%> <% @ import name "%> <html> <head> <title> Reduce the page" HTML payload "</ title> </ Head> <body> <form runat = "server"> <h3> Reduce the "HTML payload" </ h3> <p> <asp: DataGrid ID = "DataGrid1" runat = "server" enableviewstate by disabling ViewState to reduce page "HTML payload" runat = "server" = "false" borderWidth = "1px" bordercolor = "# ccccc" backcolor = "white" cellpadding = "5"> <headerstyle font-bold = "true" forecolor = "on" backcolor = "# 006699 "> </ Headerstyle> </ asp: DataGrid> </ P> </ form> </ body> </ html> <script runat =" server "></p> <p>Void Page_Load (Object Sender, Eventargs E) {</p> <p>DataSet DS = New Dataset (); DS.Readxml (Server.MAppath ("TestData.xml")); DataGrid1.datasource = DS; DataGrid1.dataBind ();</p> <p></ script></p> <p>Disabling ViewState In the above example, I disabled ViewState by setting the grid's enableViewState property to false. You can disable viewState for a single control, the entire page, or the entire application, as shown below:</p> <p>Each control (on the tag) <asp: DataGrid EnableViewState = "false"? /> Each page (in the instruction) <% @ Page EnableViewState = "false"?%> Each application (in Web.config <Pages EnableViewState = "false"? /></p> <p>Make ViewState Safe because ViewState is not formatted as a clear text, some people sometimes think it is encrypted, but there is no. Instead, ViewState is just based on Base64 encoding to ensure that the value does not change during the round-trip process, and does not consider the response / request coding used by the application.</p> <p>You can add two ViewState security levels to your application:</p> <p>Tamper-proof encryption needs to note that viewState security has a direct impact on the time required to process and present the ASP.NET page. Simply put, the higher the safety, the slower the speed. So if you don't need it, please don't add security for ViewState. Tamper-proof Although the hash code does not ensure the security of the actual data in the ViewState field, it can significantly reduce the possibility of deceiving the application through ViewState, ie, preventing the return application typically prohibits the value of the user.</p> <p>You can indicate a hash code to the ViewState field by setting the enableviewStateMac property:</p> <p><% @ Page EnableViewStateMac = true%></p> <p>EnableViewStateMac can be set on the page level, or you can set it at the application level. At the time of return, the ASP.NET will generate a hash code for the ViewState data and compare it with the hash code stored in the return value. If the hash code does not match, the viewState data will be discarded, while the control will be restored to the original settings.</p> <p>By default, ASP.NET uses the SHA1 algorithm to generate the ViewState hash code. In addition, the MD5 algorithm can also be selected by setting <MachineKey> in the Machine.config file, as shown below:</p> <p><MachineKey Validation = "MD5" /></p> <p>Encryption can use encryption to protect the actual data values ​​in the ViewState field. First, EnableViewStatmac = "True" must be set as described above. Then, set the MachineKey Validation type to 3DES. This will indicate that ASP.NET uses the Triple DES symmetrical encryption algorithm to encrypt the ViewState value.</p> <p><machinekey value = "3des" /></p> <p>ViewState Security in the web domain By default, ASP.NET will create a random authentication key and store it in local security (LSA) of each server. To verify the ViewState field created on another server, the validationKey of the two servers must be set to the same value. If you want to pass through one of the above methods, you need to provide a ViewState security settings in the web domain configuration, you need to provide a unique, shared authentication key for all servers.</p> <p>The verification key is a random string containing 20 to 64-bit password enhanced bytes, which is represented by 40 to 128 hexadecimal characters. The longer the key, the safer, so it is recommended to use 128 characters (if your computer is supported). E.g:</p> <p><MachineKey validation = "SHA1" validationKey = "F3690E7A3143C185AB1089616A8B4D81FD55DD7A69EEAA3B32A6AE813ECEECD28DEA66A23BEE42193729BD48595EBAFE2C2E765BE77E006330BC3B1392D7C73F" /></p> <p>System.Security.cryptography namespace includes RNGCryptoServiceProvider classes, using this class to generate this string, as shown in the following GenerateCryptoKey.aspx example:</p> <p><% @ Page language = "c #"%> <% @ import namespace = "system.security.cryptography"%> <html> <body> <form runat = "server"> <h3> Generate random encryption keys </ H3> <p> <ask = "radiobuttonlist1" runat = "server" repeatdirection = "horizontal"> <ask: listitem value = "40"> 40-byte </ ask: listItem> <ask: listitem value = "128" SELECTED = "true"> 128-byte </ asp: listitem> </ ask: RADIOBUTTONLIST> <ask: button id = "button1" runat = "server" οnclick = "generateKey" text = "Generate Key" > </ asp: button> </ p> <p> <asp: textbox id = "textbox1" runat = "server" textmode = "multiline" rows = "10" columns = "70" backcolor = "# eeeeee" enableViewState = "False"> Copy and paste the result of the result </ asp: textbox> </ p> </ form> </ body> </ html> <script runat = server></p> <p>Void GenerateKey (Object Sender, System.EventArgs E) {INT KeyLength = INT32.PARSE (RadiobuttonList1.Selected); // Added in the user code for the initialization page here [] BUFF = New Byte [Keylength / 2];</p> <p>RNGCRYPTOSERVICEPROVIDER RNG = New RNGCRYPTOSERVICEPROVIDER ();</p> <p>/ / The array has filled RNG.GETBYTES (BUFF) using password enhanced random bytes;</p> <p>Stringbuilder SB = New StringBuilder (Keylength); INT i; for (i = 0; i <buff.length; i ) {sb.Append (String.Format ("{0: x2}", buff [i]); } // Paste into the text box, the user can copy textBox1.text = sb.toString ();</p> <p></ script></p> <p>Summary ASP.NET ViewState is a new status service that can be tracked by the UI status based on each user. ViewState has no mystery, it just uses an old web programming skill: transfer status in a hidden form field, and applies it directly to the page processing framework. But the effect is very good - simply write and maintain very little code in a web-based form. The user may not always need it, but I think you will find it when you need it, and viewState is a very satisfactory feature that provides many ASP.NET features to page developers.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-89831.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="89831" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.039</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'qLowWcZw1n_2F_2BI7nTb3_2FilsDB0tCcsq3Nz4WFq9S1apcT3Ehb1vV_2FcwPe1kS8VIw_2FrvkjEixaHMz_2FYYZ8vQb3ew_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>