Website settings for ASP. NET MVC5 website development (9) and mvc5 website development

Source: Internet
Author: User
Tags actionlink

Website settings for ASP. NET MVC5 website development (9) and mvc5 website development

Website configuration is generally used to save some website settings. It is more appropriate to write the configuration file than to write it in the database, because the configuration file itself has a cache and is read into the cache as the website starts, which is faster, in the database, you need to create a table for a single record. The structure is not clear enough, and there is no configuration file for reading and writing. This is the basic information of the website, and the data is saved in SiteConfig. config.

I wrote a blog article 《. net MVC website configuration file read/write, in that blog has clearly written the ideas and methods, the implementation of this implementation is the same as the previous, only the KeyValueElement class and KeyValueElementCollection class were implemented at that time. In fact, these two classes are in the System. configuration namespace has been implemented, just use it.

I. Website configuration class (SiteConfig)

1. Create a folder Config in the Nninesky. Core Project.

2. Add the class SiteConfig In the Config folder.

using System.ComponentModel.DataAnnotations;
using System.Configuration;

namespace Ninesky.Core.Config
{
 /// <summary>
 /// Website configuration
 /// </ summary>
 public class SiteConfig: ConfigurationSection
 {
 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>
 /// site name
 /// </ summary>
 [Required (ErrorMessage = "*")]
 [StringLength (50, 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>
 /// Site title
 /// </ summary>
 [Required (ErrorMessage = "*")]
 [StringLength (50, ErrorMessage = "Maximum {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>
 /// Website address
 /// </ summary>
 [DataType (DataType.Url)]
 [Required (ErrorMessage = "*")]
 [StringLength (500, ErrorMessage = "Maximum {1} characters")]
 [Display (Name = "Website Address")]
 public string SiteUrl
 {
 get {return keyValues ["SiteUrl"] == null? "http: //": keyValues ["SiteUrl"]. Value;}
 set {keyValues ["SiteUrl"]. Value = value;}
 }

 /// <summary>
 /// Meta keywords
 /// </ summary>
 [DataType (DataType.MultilineText)]
 [StringLength (500, ErrorMessage = "Maximum {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, ErrorMessage = "Maximum {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, ErrorMessage = "Maximum {1} characters")]
 [Display (Name = "Copyright Information")]
 public string Copyright
 {
 get {return keyValues ["Copyright"] == null? "Ninesky Copyright": keyValues ["Copyright"]. Value;}
 set {keyValues ["Copyright"]. Value = value;}
 }

 }
}

The Siteconfig class inherits from ConfigurationSection, and inherits from this class to read and write configuration sections.
Declare a sub-element of a configuration element in the class private static ConfigurationProperty _property, the configuration entity type of the sub-element is KeyValueConfigurationCollection (key / value collection)
The code is as follows: private static ConfigurationProperty _property = new ConfigurationProperty (string.Empty, typeof (KeyValueConfigurationCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
Then Xu then declared a property private KeyValueConfigurationCollection keyValues in the class. Use keyValues to get and set the configuration section key / value collection.
 [ConfigurationProperty ("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
 private KeyValueConfigurationCollection keyValues
 {
 get {return (KeyValueConfigurationCollection) base [_property];}
 set {base [_property] = value;}
 }
Then you can use keyValues ["name"] to get the specific configuration settings.

/// <summary>
 /// site name
 /// </ summary>
 [Required (ErrorMessage = "*")]
 [StringLength (50, 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;}
 }

 
It seems that it is similar to other model classes. Knowledge Get; Set; is different.
Second, set the type and path of the configuration file
Open the web.config file of the Nniesky.web project, find configSections, and add the SiteConfig configuration section

The red box is the added type, which explains the name and type of the configuration section. Pay attention to the red line, restartOnExternalChanges is set to "false", if not set, the website will be restarted after the configuration file is modified.

Add the path of the configuration file at the end of the configuration file </ configuration>

The red box in the figure is the added content, indicating that the location file of SiteConfig is named SiteConfig.config in the Config folder of the website directory.
Then add the Config folder in the project, and then add the configuration file 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 = "Keywords," />
 <add key = "MetaDescription" value = "Description" />
 <add key = "Copyright" value = "Ninesky Copyright <a> 11 </a>" />
</ SiteConfig>

The key names in the configuration file correspond to the property names of SiteConfig.
Three, controller and view
1. Reading configuration files
In Ninesky.Web / Areas / Control / Controllers [right]-> add-> controller, enter the controller name ConfigController.
Add method SiteConfig method in the 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 very simple, using the GetSection method of WebConfigurationManager to read the configuration information.

Right-click to add a view to display the attributes.

@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 ("Home", "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, "", new {@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 (model => model.SiteTitle, new {htmlAttributes = new {@class = "form-control"}})
 @ Html.ValidationMessageFor (model => model.SiteTitle, "", new {@class = "text-danger"})
 </ div>
 </ div>

 <div class = "form-group">
 @ Html.LabelFor (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 (model => model.MetaKeywords, new {htmlAttributes = new {@class = "form-control"}})
 @ Html.ValidationMessageFor (model => model.MetaKeywords, "", new {@class = "text-danger"})
 </ div>
 </ div>

 <div class = "form-group">
 @ Html.LabelFor (model => model.MetaDescription, htmlAttributes: new {@class = "control-label col-md-2"})
 <div class = "col-md-10">
 @ Html.EditorFor (model => model.MetaDescription, new {htmlAttributes = new {@class = "form-control"}})
 @ Html.ValidationMessageFor (model => model.MetaDescription, "", new {@class = "text-danger"})
 </ div>
 </ div>

 <div class = "form-group">
 @ Html.LabelFor (model => model.Copyright, htmlAttributes: new {@class = "control-label col-md-2"})
 <div class = "col-md-10">
 @ Html.EditorFor (model => 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">
 <input type = "submit" value = "Save" class = "btn btn-default" />
 </ div>
 </ div>
 </ div>
}

2. Saving configuration files.
Add a SiteConfig method of type [HttpPost] 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 '> Back </a> "}});
 }
 else return View (_siteConfig);
 }
 }

The code is also very simple. It is the same as reading the configuration file. Use the GetSection method of WebConfigurationManager to read the configuration information into _siteConfig, and then use TryUpdateModel <SiteConfig> (_ siteConfig) to bind the information submitted by the view.
If the binding is successful, use the _siteConfig.CurrentConfiguration.Save () method to save the configuration information (this method inherits from ConfigurationSection and does not need to be implemented by yourself).
The effect is like
=================================================
 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 it will be helpful to everyone's learning, and I hope everyone will support the home of helpers.

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.