ASP. net mvc for general settings, asp. netmvc for General

Source: Internet
Author: User

ASP. net mvc for general settings, asp. netmvc for General

There are several ways to implement settings on the website, including serializing the settings class and saving it to the file (for example, using XML serialization and then saving it in XML format ), or save the settings to the database.

The method for saving data to the database is to use the set item as the key, set the value as the value, and save it as a key-value pair.

The following example shows how to save data to a database. The first step is to set the table structure of the information database:

 

Name is the set item, and Value is the set Value. The corresponding object classes are as follows:

public class Setting : ISettings    {        public int Id { get; set; }        public string  Name { get; set; }        public string Value { get; set; }    }
View Code

Here the Entity Framework is used, and the following is the context Entity class of the database:

Public partial class SettingContext: DbContext {public SettingContext (): base ("name = MyConnection") {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {Database. setInitializer <SettingContext> (null); modelBuilder. events. add (new SettingMap (); base. onModelCreating (modelBuilder);} public IQueryable <Setting> Table {get {return Set <Setting> () ;}} public IQueryable <Set Ting> TableNoTracking {get {return Set <Setting> (). asNoTracking () ;}} public void Insert (Setting entity) {if (entity = null) {throw new ArgumentException ("entity");} Set <Setting> (). add (entity); SaveChanges ();} public void Update (Setting entity) {if (entity = null) {throw new ArgumentException ("entity ");} set <Setting> (). attach (entity); Entry (entity ). state = EntityState. modified; SaveChan Ges ();} /// <summary> // load "Settings" /// </summary> /// <typeparam name = "T"> the interface ISettings must be set </typeparam> /// <returns> </returns> public T LoadSetting <T> () where T: ISettings, new () {// create a set instance, and then assign the value var setting = Activator to its attribute. createInstance <T> (); Type t = typeof (T); // obtain all attributes PropertyInfo [] props = t. getProperties (); // obtain all settings in the database var allSetting = TableNoTracking. toList (); if (allSetting! = Null & allSetting. Count> 0) {foreach (PropertyInfo p in props) {if (! P. CanRead |! P. canWrite) {continue;} string key = t. name + ". "+ p. name; key = key. trim (). toLowerInvariant (); // convert it to lower case var obj = allSetting. where (s => s. name = key ). firstOrDefault (); if (obj = null) {continue;} string valueStr = obj. value; // determines whether it can be converted to if (! TypeDescriptor. GetConverter (p. PropertyType). CanConvertFrom (typeof (string) {continue;} if (! TypeDescriptor. getConverter (p. propertyType ). isValid (valueStr) {continue;} object value = TypeDescriptor. getConverter (p. propertyType ). convertFromInvariantString (valueStr); p. setValue (setting, value) ;}} return setting ;} /// <summary> /// Save the settings /// </summary> /// <typeparam name = "T"> the interface ISettings must be set </typeparam> // /<param name = "setting"> </param> public void SaveSetting <T> (T setting) where T: IS Ettings, new () {var allProperties = typeof (T). GetProperties (); var allSettings = Table. ToList (); foreach (PropertyInfo prop in allProperties) {if (! Prop. CanRead |! Prop. CanWrite) {continue;} // determines whether the if (! TypeDescriptor. getConverter (prop. propertyType ). canConvertFrom (typeof (string) {continue;} string key = typeof (T ). name + ". "+ prop. name; key = key. trim (). toLowerInvariant (); dynamic value = prop. getValue (setting, null); if (value = null) {value = "";} var obj = allSettings. where (s => s. name = key ). firstOrDefault (); // it needs to be converted to string valueStr = TypeDescriptor. getConverter (prop. propertyType ). ConvertToInvariantString (value); // if an existing setting exists, update it. if not, add if (obj! = Null) {obj. value = valueStr; Update (obj);} else {obj = new Setting {Name = key, Value = valueStr}; Insert (obj );}}}}
View Code

Because generic constraints are required, you must set the class to implement the ISettings interface.

EF ing class:

public class SettingMap : EntityTypeConfiguration<Setting>    {        public SettingMap()        {            this.ToTable("Setting");            this.HasKey(s => s.Id);            this.Property(s => s.Name).HasMaxLength(512);        }    }
View Code

Basic settings:

/// <Summary> /// Basic settings /// </summary> public class BaseSetting: ISettings {[DisplayName ("website name")] public string SiteName {get; set;} [DisplayName ("record filing number")] public string SiteICP {get; set;} [DisplayName ("Contact Info")] public string SiteTel {get; set ;} [DisplayName ("Copyright information")] public string Copyright {get; set;} [DisplayName ("Status")] public bool Status {get; set ;} [DisplayName ("cache time")] public int CacheTime {get; set ;}}
View Code

The Controller is as follows:

public class SettingController : Controller    {        SettingContext settingContext = new SettingContext();        // GET: Setting        public ActionResult Index()        {            return View();        }        public ActionResult Base()        {            var setting = settingContext.LoadSetting<BaseSetting>();            return View(setting);        }        [HttpPost]        public ActionResult Base(BaseSetting model)        {            if (ModelState.IsValid)            {                settingContext.SaveSetting<BaseSetting>(model);            }            return View(model);        }    }
View Code

View code (in fact, the Edit view is used ):

 

@model SettingDemo.Models.BaseSetting@{    ViewBag.Title = "Base";}View Code

Browser front-end:

Enter settings, save, and view the database

Here, the setting item uses the class name, attribute name, or full name (full namespace, class name, and attribute name). You only need to modify the code as appropriate. To extend the settings class, you need to implement the ISettings interface like BaseSetting.

Reference: nopcommerce mall System

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.