Configuration and Views - asp.net

I've been developing an application using asp.net MVC, and I have some configurations that influences in process of render a view. For example, a user can choose (in an configuration of system) if a field should appear for a management of records in an area of the system. So, I have an class called AppConfiguration has some properties to represent this configurations.
I guess I need to cache an object of AppConfiguration, and make a ViewModel base class and inherits from my viewmodel, for example:
public class BaseViewModel {
public AppConfiguration Config { get; set; }
}
public class DocumentViewModel : BaseViewModel {
public Document Document { get; set; }
}
and make typed views using "DocumentViewModel" to check the properties if this kind of document is able to render or not ? is it works ? Or is there any other better way to do something like this ?
Thanks all and sorry for my english!
Cheers

I'd suggest that you write an associated metadata provider for your view model and then use default templated views in MVC 2.

Related

What is difference between Model and ViewModel in asp.net core mvc? [duplicate]

This question already has answers here:
What is ViewModel in MVC?
(16 answers)
Closed 5 years ago.
I have a Account class for account models.
public class Account
{
[Key]
public Int64 UID { get; set; }
[Required]
public string ID { get; set; }
[Required]
public string PassWord { get; set; }
[Required]
public string UserName { get; set; }
}
My project is not a code first project and this is a model class for database 'Account'.
But I use only two properties in login view, string ID and string PassWord.
So I can not use ModelState.Isvalid() in the login controller when I check the validation of model because I use
just two properties...
So I searched about that then, now I found about 'ViewModel' which is the model class for view.
Then I created a new class 'AccountViewModel' and then I mapped this with view instead of 'Account' model.
Did my way was right?
I understood the ViewModel is a model class just for View.
And The model class is for all. (like a global meaning...? for DB,view and so on)
What is different between Model and ViewModel class?
May I get some a nice way to solve this?
As the name says, view model is very specific to the view.It will be a simple POCO with only those properties needed for the view.
Your other model class is your entity models. So if you are using EF code first approach, you need entity class definitions from which EF will generate the database tables. So basically these entity classes look very similar to your db schema structure.
By creating a view model, you are removing the strong coupling of your entity classes to the UI layer. Now your UI layer is independent of your entity classes and if you ever decide to change the data access code from EF to something else, you do not need to touch the views at all.You simply need to update the mapping part(from the view model to the data access/service layer entities)
View models sometimes looks very similar to your entity models, especially if your entity model is a simple table/class.
In your case, since your view is passing a userid and password, you need a simple view model which has only those 2 properties. When user submits the form,you can read the values and use it to build an domain entity class object as needed.
public class LoginViewModel
{
public string UserId { set;get;}
public string Password { set;get; }
}
You can use data annotations with the view models. The MVC model validation framework these data annotations to do the validations. For example, since user should enter a UserId and Password, you may decorate them with appropriate annotations.
public class LoginViewModel
{
[Required]
public string UserId { set;get;}
[Required]
public string Password { set;get; }
}
The [Key] attribute is more useful when you define an entity class. So i would not think it is needed for a view model. Remember view model is more like a UI concern. It has no idea about your underlying data storage mechanism at all.
Some of the most used attributes with view model properties are
Required
MinLength
Range
Url
Phone
StringLength
DataType

asp net mvc adding a new property to model

I'm new in asp.net mvc. I'm trying to learn entity framework after the database has been created by the first code starting, i m adding a new porperty to model, but controller and view are not updating themselves automatically.
public class test
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname{ get; set; }
}
in this simple I add Surname property after database created. I update database, but view and controller side do not update themselves automatically.
So should I make all changes manually like changing controller "create edit delete" post action.
thanks for answer
You most likely used scaffolding to create them first. If you want to have the properties listed in the view you need to recreate the scaffolding so it knows that property exists. To do that right click on the controller folder add new scaffolded item, like you did before.
You need to update the binding white list so your new property will be included, For this use Ctrl+Shift+B [For Visual Stdio]
after that do the Migration and update the database.

ASP.Net Model without DbContext?

I am new to ASP.Net, if my question sounds very basic, please be polite.
I have created a ASP.Net MVC4 project. A page in the application will display names of the files in tabular form.
The names of the files are obtained by finding files in a particular folder on the server. So there is no need for me to have a database for model.
When user opens the page, the server side code will list all the files in the directory and should return a list of Strings.
I am following ASP.Net MVC tutorial here and it appears I have to have a DBContext class and also a database. In my case that's not needed
So that question is can I add my model without having to add code like below and still be able to use the feature of model ? any simple example would be great.
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
Any class can serve as a model in this case. For example, if you just want to have a Movie model, you can have something as simple as this:
public class Movie
{
public string Title { get; set; }
}
A view can bind to that model, to an enumeration of that model, etc.
For fetching your data from the file system, one approach could be a simple factory method on that model. Maybe something like this:
public class Movie
{
public string Title { get; set; }
public static IEnumerable<Movie> GetMovies()
{
// get the list of movies from the file system, for example as a list of strings
var movies = SomeFileSystemInteraction();
return movies.Select(m => new Movie { Title = m });
}
}
Then in your controller you can get the list of movies to bind to the view:
public ActionResult Index()
{
return View(Movie.GetMovies());
}
There's no need for a database, it's just used in tutorials because it's the most common case. But you can bind your views to any object you'd like.
You do not need that MovieDBContext class if you are not dealing with database. But having a model is a good idea to represent your entity(in this case the Folder). It is just a POCO class.
public class Folder
{
public string Name { set;get;}
public int NumberOfchilds { set;get;}
//Other properties as needed.
}
Now you can use the Model class to pass data between differnt places. For example. You can move the code which reads the data from file system to a Service class method and the method can return a list of this class/A single instance of this class as needed. Your controller action method can call the service method.
public class FolderService
{
public Folder GetRecentlyCreatedFolder()
{
var folder=new Folder();
//Set the properties of this object
// folder.Name="MySecret";
return folder;
}
}
and in your Action method
public ActionResult Items()
{
var srv=new FolderService();
var recentFolder=srv.GetRecentlyCreatedFolder();
return View(recentFolder);
}
Yes, you can use a model which is not stored in a database at all. Your case sounds like an obvious example.
Model, View, Controller makes database access easily abstractable but doesn't necessitate a database.
As much as I like entity framework I've never loved how most tutorials for MVC seem to marry the two - They are essentially unrelated and I think it really muddies the waters for a lot of programmers new to the framework.
All you need for a model is just a plain old class. Instead of using the dbcontext you'd simply use whatever code you need to load your data.

Overriding validation attribute from a base Model

i have a MVC controller called MyController with an action called MyAction. For other hand i have a Model called MyModel, and all this classes are in a project called Portal.Website (Asp.net MVC3 Application) that i use as a generic website and that store common functionalities for custom websites that i will add in the future.
For other hand i have another website project with a reference to Portal.Website project called Portal.Website.MyCustomWebsite.
This is the viewmodel MyModel.cs in the generic website part:
namespace Portal.Website
{
public class MyModel
{
[Required(ErrorMessage="The field Name is required.")]
[Display("MyPropertyOriginal")]
public virtual string Name{get;set;}
}
}
This is the controller and action in the generic website part:
namespace Portal.Website
{
public class MyController: Controller
{
[HttpPost]
public ActionResult MyAction(MyModel model)
{
if(Model.IsValid)
....
//My issue: Im getting the error message in english, not the overridden one.
}
}
}
This is the viewmodel that i created in the custom part:
namespace Portal.Website.MyCustomWebsite
{
public class MyModel: MyModel
{
[Required(ErrorMessage="My error message in other language.")]
[Display("MyPropertyOverriden")]
public override string Name{get;set;}
}
}
My problem:
I would like to override the ErrorMessage of the Required attribute. For this reason i created a new Model in my custom project. For other hand i would like to use the Controller/Action (MyController/MyAction) that is already defined in my common part.
Do you know if this is possible? Im only getting the issue with the Required attribute, but with the Display one its working perfect.
Thanks in advance.
Greets.
Jose.
You may want to check out this article that suggests two possible solutions :
http://www.codeproject.com/Articles/130586/Simplified-localization-for-DataAnnotations
I've found it was making more sense to re-create some DataAnnotation classes with my custom logic.
MVC3 comes with better support for I18N (internationalisation) than it's predecessors - you can pass the RequiredAttribute the type of your resource class and the resource key and the error message will be displayed in whichever language is most appropriate:
[Required(ErrorMessageResourceType = typeof(MyResources), ErrorMessageResourceName = "ResourceKey")]
public override string Name { get; set; }

Using autofac to inject properties into asp.net pages: Overriding PropertyInjectionModule behaviour to inject values/settings

Is it possible to inject values/settings into ASP.NET Pages via autofac's PropertyInjectionModule? I get the impression that default handler behavior is to search for properties and find any types that match services in the container.
eg for a page:
public class MyPage: System.Web.UI.Page {
public IDataProvider DataProvider { get; set; }
public bool SomeSetting {get; set; }
public bool AnotherSetting { get; set; }
public string MySettings { get; set; }
// stuff
}
I thought maybe you could specify properties:
builder.RegisterType<MyPage>()
.WithProperty("SomeSetting", true)
.WithProperty("AnotherSetting", false)
.WithProperty("MySettings", "do-re-mi");
but it doesn't seem to work.
I realise I could setup an IMyPageConfig interface and provide settings that way but these are optional properties that may or may not need to be set.
IoC in ASP.NET Pages is a bit limited - although the module is injecting properties into the page, it can't really use Autofac's regular dependency injection features.
In WebForms the way people typically get around this is to use something like Model-View-Presenter, where the page is just a 'dumb' view and the presenter is where the logic (and proper dependency injection) takes place.
Check out http://webformsmvp.com/ - I think there is an IoC example and Autofac support available there.

Resources