We implement here in just 5 minutes a C# method to read AppSettings from the web.config file, and display an error Alert using the Twitter Bootstrap , in case that some value was not found at the AppSettings :
How to Read AppSettings Values from Web.config in MVC
We'll use the Configuration namespace, so add the using as follows:
Happy programming.....
by Carmel Schvartzman
Next, add the following method (to some MVC Controller, or to some specific Utilities class):
Here we read the AppSettings and, in case that the Key was not found, we throw an exception. This is the code to copy-paste:
private string ReadAppSettings(string key)
{
string value = ConfigurationManager.AppSettings[key];
if (!String.IsNullOrEmpty(value))
{
return value;
}
else
throw new Exception("AppSettings Values not found");
}
Now, you can catch the exception, and return the Exception's Message inside some Tuple<>, as follows:
catch (Exception ex)
{
return new Tuple<bool, string>(false, ex.Message);
}
Rebuild and run your MVC app, and browse to the MVC View.
This is a snapshot of an MVC View using the AppSettings Reader above:
If you like this Bootstrap style, take a look at the following 5 minutes Tutorial about using the Bootstrap Alert component .
by Carmel Schvartzman
כתב: כרמל שוורצמן
No comments:
Post a Comment