MVC5 website development-9 website settings and mvc5 website development settings

Source: Internet
Author: User
Tags configuration settings

MVC5 website development-9 website settings and mvc5 website development settings

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.

Directory

Overview of MVC5 website development

Create a project for MVC5 website development 2

MVC5 website development 3 data storage layer function implementation

Architecture and basic functions of the four business logic layers of MVC5 website development

5-display layer architecture of MVC5 website development

6 administrators of MVC5 website development 1. logon, verification, and logout

6 administrators of MVC5 website development 2. add, delete, Reset Password, Change Password, list browsing

Seven user functions of MVC5 website development 1. Role background management

Seven users in MVC5 website development function 2 adding and browsing users

7. User functions of MVC5 website development 3. Modification and deletion of user data

Add, modify, and delete functions of the eight columns of MVC5 website development



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.

1. Site Configuration (SiteConfig)
1. Create a new 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)

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 &amp; lt; a &amp; gt; 11 &amp; lt; / A &amp; gt;" / >
</SiteConfig>
The key name in the configuration file corresponds to the property name of siteconfig.
3、 Controllers and views
1. Reading configuration file
Right click ninesky.web/areas/control/controllers - > Add - > controller, and enter the controller name configcontroller.
Add method siteconfig method to 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. Use the getsection method of webconfiguration manager to read out the configuration information.
Right click to add a view to display the attributes.
@model Ninesky.Core.Config.SiteConfig
[H]
Viewbag.title = "site settings";
}
@section SideNav{@Html.Partial("SideNavPartialView")}
<ol class="breadcrumb">
<li>< span class = "glyphicon glyphicon 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. Save the configuration file.
Add another 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 the website 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, use the getsection method of webconfiguration manager 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 the configurationsection and does not need to be implemented by itself).
Effects such as
=================================================
Code download: http://git.oschina.net/ninesky/ninesky
Download method: http://www.cnblogs.com/mzwhj/p/5729848.html

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.