asp.net MVC5 Web site development Site Settings (ix) _ Practical skills

Source: Internet
Author: User
Tags reserved actionlink

The site configuration is typically used to save some settings for the site, writing in a configuration file is more appropriate than writing in a database, because the profile itself has a cache, and as the site starts reading into the cache, the speed is faster, and saving in the database to create a separate table for a record is not structurally clear, and read and write is also not easy to implement configuration files. This time to do is the basic information of the website, the data is kept in Siteconfig.config.

In 14, wrote a blog, ". Net MVC Web site configuration file read and write," In that blog, the ideas and methods have been written clearly, this time the realization of the same thinking as the last time, Just that oneself realized Keyvalueelement class and Keyvalueelementcollection class, in fact, these two classes in the System.Configuration namespace have been implemented, directly use the line.

I. Site Configuration class (SiteConfig)

1. Create new folder config in Nninesky.core project

2, add Class SiteConfig in config folder.

Using System.ComponentModel.DataAnnotations;

Using System.Configuration; namespace Ninesky.Core.Config {///<summary>///Web Site Configuration Class///</summary> public class Siteconfig:configura tionsection {private static ConfigurationProperty _property = new ConfigurationProperty (string.

 Empty, typeof (Keyvalueconfigurationcollection), NULL, configurationpropertyoptions.isdefaultcollection); [ConfigurationProperty ("", Options = configurationpropertyoptions.isdefaultcollection)] Private
 Keyvalueconfigurationcollection KeyValues {get {return (keyvalueconfigurationcollection) base[_property];}
 set {Base[_property] = value;} ///<summary>///website name///</summary> [Required (errormessage = "*")] [Stringlength (errormessage = "Maximum {1} characters")] [Display (name = Site name)]] public string SiteName {get {return keyvalues["SiteName"] = = null. String. empty:keyvalues["SiteName"]. Value; } set {keyvalues["SiteName"]. Value = value; }}///<summary>///websiteTitle///</summary> [Required (errormessage = "*")] [Stringlength (errormessage = "up to {1} characters")] [Display (Name =] Site title "]] public string Sitetitle {get {return keyvalues[" sitetitle "] = = null. String. empty:keyvalues["Sitetitle"]. Value; } set {keyvalues["Sitetitle"]. Value = value; }///<summary>///Web site address///</summary> [DataType (Datatype.url)] [Required (errormessage = "*")] [stri Nglength (errormessage = "up to {1} characters")] [Display (Name = Site address)] public string SiteURL {get {return keyvalues[' Sit Eurl "] = = null? "http://": keyvalues["SiteURL"]. Value; } set {keyvalues["SiteURL"]. Value = value; }///<summary>///meta keywords///</summary> [DataType (Datatype.multilinetext)] [stringlength] [Error  Message = "Up to {1} characters")] [Display (Name = "meta keyword")] public string Metakeywords {get {return keyvalues["metakeywords"] = null? String. empty:keyvalues["Metakeywords"]. Value; } set {keyvalues["Metakeywords"]. Value = value;

 }
 }<summary>///meta Description///</summary> [DataType (Datatype.multilinetext)] [Stringlength (1000, Errormessag E = "Max {1} characters")] [Display (Name = "meta description")] public string Metadescription {get {return keyvalues["metadescription"] = null? String. empty:keyvalues["Metadescription"]. Value; } set {keyvalues["Metadescription"]. Value = value; ///<summary>///Copyright Information///</summary> [DataType (Datatype.multilinetext)] [Stringlength (1000, Errorme Ssage = "Up to {1} characters")] [Display (Name = "copyright Information")] public string, copyright {get {return keyvalues["copyright"] = = null? "Ninesky All rights reserved": keyvalues["copyright"]. Value; } set {keyvalues["Copyright"]. Value = value;

 }
 }

 }
}

The SiteConfig class inherits from the ConfigurationSection and inherits from this class to be able to read and write configuration sections.

Declare a child element of a configuration element in a class private static ConfigurationProperty _property, the configuration entity type of a child element is a keyvalueconfigurationcollection (key/value collection).

Copy Code code as follows:
private static ConfigurationProperty _property = new ConfigurationProperty (string. Empty, typeof (Keyvalueconfigurationcollection), NULL, configurationpropertyoptions.isdefaultcollection);

Xu then declares a property in the class private Keyvalueconfigurationcollection keyvalues. Use KeyValues to get, set configuration section key/value collection.

 [ConfigurationProperty ("", Options = configurationpropertyoptions.isdefaultcollection)]
 Private Keyvalueconfigurationcollection keyvalues
 {get
 {return (keyvalueconfigurationcollection) base[_ Property];
 set {Base[_property] = value;}
 } 

You can then use the keyvalues["name"] to get the settings specific configuration.

<summary>
 ///website name
 ///</summary>
 [Required (errormessage = "*")]
 [Stringlength (50 , errormessage = "up to {1} characters")]
 [Display (name = Site name)] public
 string SiteName {get
 {return keyvalues["SiteName"] = = null? String. empty:keyvalues["SiteName"]. Value; }
 set {keyvalues["SiteName"]. Value = value; }
 }


Seems to be similar to other model classes, knowledge get;set, different.

Ii. Setting the type and path of the configuration file

Open the Web.config file for the Nniesky.web project, locate the configsections, and then add the SiteConfig configuration section

The red box is added to the type, describes the configuration section name and type, note the Red Line section, restartOnExternalChanges set to "false", if not set, the configuration file will be modified to restart the Web site.

At the end of the configuration file </configuration> add the path to the configuration file

The red box portion of the figure is added to indicate that the SiteConfig location file is named Siteconfig.config under the Web Site Directory Config folder.

Then add the Config folder to your project, and then add a profile named Siteconfig.config.

<?xml version= "1.0" encoding= "Utf-8"?>
<SiteConfig>
 <add key= "SiteName" value= "Ninesky"/ >
 <add key= "Sitetitle" value= "1133"/> <add key=
 "SiteURL" value= "http://mzwhj.cnblogs.com"/>
 <add key= "metakeywords" value= keyword, "/> <add key=" metadescription "value="
 description "/> <add
 key = "Copyright" value= "Ninesky All rights reserved <a>11</a>"/>
</SiteConfig>

The key name in the configuration file corresponds to the SiteConfig property name.

III. Controllers and views
1, the configuration file read

In the Ninesky.web/areas/control/controllers "right"-> Add the-> controller, enter the controller name Configcontroller.

Add method SiteConfig method in control

<summary>
 ///Site Settings
 ///</summary>
 ///<returns></returns>
 Public ActionResult SiteConfig ()
 {
 SiteConfig _siteconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("~"). GetSection ("SiteConfig") as Ninesky.Core.Config.SiteConfig;
 Return View (_SiteConfig);
 }

The code is simple, using WebConfigurationManager's GetSection method to read the configuration information.

Right-click to add a view to display a property.

@model Ninesky.Core.Config.SiteConfig @{viewbag.title = "Site Settings";} @section sidenav{@Html. Partial ("Sidenavpartialview")} <ol class= "breadcrumb" > <li><span class= " Glyphicon glyphicon-home "></span> @Html. ActionLink (" homepage "," Index "," Home ") </li> <li>@ Html.ActionLink ("System Settings", "Index") </li> <li class= "active" > Site Settings </li> </ol> @using ( Html.BeginForm ()) {@Html. AntiForgeryToken () <div class= "Form-horizontal" > @Html. ValidationSummary (True, "", NE w {@class = "Text-danger"}) <div class= "Form-group" > @Html. Labelfor (model => model.  SiteName, htmlattributes:new {@class = "Control-label col-md-2"}) <div class= "col-md-10" > @Html. Editorfor (model => model. SiteName, new {htmlattributes = new {@class = "Form-control"}}) @Html. validationmessagefor (model => model. SiteName, "", new {@class = "Text-danger"}) </div> </div> <div class= "Form-group" > @Html. labelfor (Model => mOdel. Sitetitle, htmlattributes:new {@class = "Control-label col-md-2"}) <div class= "col-md-10" > @Html. Editorfor (Mode L => model. Sitetitle, new {htmlattributes = new {@class = "Form-control"}}) @Html. validationmessagefor (model => model. Sitetitle, "", new {@class = "Text-danger"}) </div> </div> <div class= "Form-group" > @Html. Labelfo R (model => model. SiteURL, htmlattributes:new {@class = "Control-label col-md-2"}) <div class= "col-md-10" > @Html. Editorfor (model => model. SiteURL, new {htmlattributes = new {@class = "Form-control"}}) @Html. validationmessagefor (model => model. SiteURL, "", new {@class = "Text-danger"}) </div> </div> <div class= "Form-group" > @Html. Labelfor ( Model => model. Metakeywords, htmlattributes:new {@class = "Control-label col-md-2"}) <div class= "col-md-10" > @Html. Editorfor (M Odel => model. Metakeywords, new {htmlattributes = new {@class = "Form-control"}}) @Html. Validationmessagefor (model => model. Metakeywords, "", new {@class = "Text-danger"}) </div> </div> <div class= "Form-group" > @Html. Labe Lfor (model => model. Metadescription, htmlattributes:new {@class = "Control-label col-md-2"}) <div class= "col-md-10" > @Html. EditorFo R (model => model. Metadescription, new {htmlattributes = new {@class = "Form-control"}}) @Html. validationmessagefor (Model => MODEL.M Etadescription, "", new {@class = "Text-danger"}) </div> </div> <div class= "Form-group" > @Html. La Belfor (model => model. Copyright, htmlattributes:new {@class = "Control-label col-md-2"}) <div class= "col-md-10" > @Html. Editorfor (Mode L => model. Copyright, new {htmlattributes = new {@class = "Form-control"}}) @Html. validationmessagefor (model => model. Copyright, "", new {@class = "Text-danger"}) </div> </div> <div class= "Form-group" > <div class = "Col-md-offset-2 col-md-10" &Gt

 <input type= "Submit" value= "Save" class= "btn btn-default"/> </div> </div> </div>}

2, the configuration file preservation.

Add another [HttpPost] type of SiteConfig method to the controller.

[ValidateInput (false)]
 [Validateantiforgerytoken]
 [HttpPost]
 Public ActionResult SiteConfig (formcollection form)
 {
 SiteConfig _siteconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("~"). GetSection ("SiteConfig") as Ninesky.Core.Config.SiteConfig;
 if (tryupdatemodel<siteconfig> (_siteconfig))
 {
 _siteconfig.currentconfiguration.save ();
 Return View ("Prompt", new Prompt () {Title = "modified successfully", message = "Successfully modified Site Settings", Buttons = new List<string> {"<a href = ' "+url.action (" SiteConfig ") +" ' class= ' btn btn-default ' > Return </a> "}});
 else return View (_siteconfig);
 }
 }

The code is also very simple, the same as reading the configuration file, using the WebConfigurationManager GetSection method to read the configuration information into the _SiteConfig, and then use the Tryupdatemodel<siteconfig The information submitted by the > (_siteconfig) Binding view.

If the binding succeeds, the _siteconfig.currentconfiguration.save () method is used to save the configuration information (this method inherits from the ConfigurationSection and does not have to be implemented by itself).

The effect of the following figure

=================================================
Code Download: Http://git.oschina.net/ninesky/Ninesky
Download method: http://www.cnblogs.com/mzwhj/p/5729848.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.