ASP.Net MVC model translate language for display - asp.net-mvc

I am working on multi-language enabled mvc application. I have a translation table in database, which I bring on application start and save it in application memory.
The database structure is {TextId, LanguageId, Translation}. TextId is assigned to each UI element (like label, validators, dropdown list text, etc.). There is an admin interface to manage the translation text.
I want to know what is a good way to show translated text on UI, and where is the best place to do the actual translation. I do not want to use the resource manager, since the database is being used in other Asp & Asp.Net webforms applications.
Here is the model (for example)
public class UserLoginModel
{
[Required(ErrorMessage="ER001")]
[Range(6,10,ErrorMessage="ER002")]
[Display(Description="TX001", Name="TX002")]
public string LoginId { get; set; }
[Required(ErrorMessage="ER003"), DataType(DataType.Password)]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
Language Id will be in Session["LanguageId"], and TranslationText is in Application variable.
Models reside in separate project, hence there is not direct access to session, but I can use DI (don't know whether it is a good practice!)
Here are following things I was considering:
Write Html helper extension like #Html.TranslateText("TX001"). I started with this method, but soon realized that #Html.ValidationMessage accepts only one message, irrespective of multiple validator attributes on property. I cannot use EditorFor templates either.
Use javascript to replace text ids with appropriate messages
Use reflection on model and replace text ids for attributes.
I am leaning towards option 3, by extending ModelMetadataProvider, or writing action filter attribute, or in EditorForModel template.
I am very confused on how to proceed. I am still in process of learning MVC. Hence. I would like to ask experts on how to handle this problem in best possible way.
Thanks,

Related

Dynamically change models and controllers after publishing website in ASP.NET Core MVC

I'm using ASP.NET Core MVC 2. I need to operator can change some elements of Models or view codes. How I can code or design for it.
For example: I have a "news" model and I want to operator (final user of website, who can't code or access to visual studio) can add this to "news" model:
public string ImageUrl { get; set; }
and also can change the database without coding.
Thanks
If you want to design a completely extensible model, you could use something called Entity–attribute–value model (EAV).
Your model might have a couple common attributes like Title and Summary. Then you might have a list of Custom Fields, the first of which could be ImageUrl. You could create your own class called CustomField or something similar, which would have properties such as FieldName, and DataType.
public string Title { get; set; }
public string Summary { get; set; }
public List<CustomField> CustomFields { get; set; }
You would then have a table full of custom field values and the tables they belong to. It gets pretty complex.
When you want to automatically reflect your model changes to the database, you will need an ORM framework like EF (Entity Framework). You can check more here.
In order for your case to happen is to build your own configuration platform that may use several tools and mechanincs that will allow you to generate code and then compile it. Such as T4 and more.
In general, this is a very hard task to accomplish and even big experienced teams would have troubles to build something similar.
I can not post any code, as this would only seem a desperate approach.

Localization in DDD

I have a list of physics parameters (like Pressure, Voltage and etc.) accessible to all users from all tenants (multi-tenant application). Now, I need a way to display appropriate language to different users.
Parameter is an aggregate root:
class Parameter
{
public string Name { get; }
public string Description { get; }
}
I need a way to localize both name and description. My first approach was this:
class Parameter
{
public IDictionary<Locale, NameAndDescription> Info { get; }
}
but I feel somehow that this is not correct.
Also, administrators will want to write different translations in the UI. But users will want to see only selected translation (switchable if needed).
How should I solve this problem? Should I remove it completely from domain? Can my application layer have methods to write appropriate translations (facilitating administrators)? Should I resolve current locale from context or should I expect it to be passed to URI/DTO when hitting endpoints? Any other information on localization in DDD would be appreciated.
Localization should be in another bounded context, probably implemented using a CRUD architecture as there are no business rules/invariants that need to be protected. Then, in the UI, using translation methods that access that bounded context, names of the parameters are displayed to the user according to their locale and/or administration settings.
Put it other way, localization does not seem to play any role inside your core domain, they do not participate in protecting the domain invariants.

MVC Web form without database

I'm in the process of refitting a website that I'd previously built using ASP.net with VB in the code-behind, into MVC with VB so that it's more responsive to different screen sizes and device types.
So far I've been able to replicate six of the pages plus the Site.Master files. Now I'm turning my attention to the Contact page which in asp.net takes data from a form, validates it for completion and data-type compliance and then passes it to the code-behind which uses it to generate an email.
I've done quite a lot of reading which suggests using a Model but all the examples I've found then use that Model to populate or query a database using LINQ.
How can I do this without a database?
The M in MVC stands for Model, not Mdatabase. You can use whatever you want as the model. Most applications use a database and most .NET applications use EF to access a database (or at least Microsoft want it that way) but you can use whatever you want.
Using a database engine is recommended as permanent storage, but essentially you can create model class for contact page without involving a database like this:
public class Contact
{
[Required]
public String Name { get; set; }
[Required]
public String EmailAddress { get; set; }
}
And you can use LINQ/lambda expressions after wrapping your model class into a collection (e.g. List), as example:
var list = new List<Contact>();
list.Add(new Contact { ... }); // adding items to the list
// Lambda syntax
var name = list.Select(x => x.Name); // returns a value from the list
// LINQ syntax
var email = (from item in list
select item.EmailAddress);
Then you can convert the code-behind logic to a controller action method as ActionResult each for GET and POST request. Afterwards, Redirect, RedirectToAction or simply return View() after data submission can be used for page handling.
About responsive page design to work with different screen sizes and device types, MVC itself not designed to present responsive layouts by default. You need to alter some HTML & CSS-related attributes, as similar problem here:
How to make an MVC web application adjust to automatically fit different screen sizes
NB: Since your problem doesn't include any code, the provided codes are just examples as figure to what should be done.

What is the right design pattern for custom template types in ASP.NET MVC?

Here's my situation: I've got a number of specialized object types in my application, and I'm following the standard convention for displaying them with custom templates in the /Shared/DisplayTemplates folder, and editing them with templates in /Shared/EditorTemplates. But I also want to be able to display a custom filter template for each type, so I'd like to add a /Shared/FilterTemplates folder, and implement my own #Html.FilterFor method, so that showing a Filter template is exactly like showing a Display or Editor template.
Does this seem like the best way to handle this situation, or is there a more correct/elegant way to do this in MVC? Thanks in advance.
I'm always using EditorTemplates when data is sent back to server. I assume the user can submit the filter to the server to perform the actual filtering.
When creating filters I prefer to create a model for the filter like:
public class UserListFilterModel
{
public string Username { get; set; }
public bool IsEnabled { get; set; }
}
The view for UserListFilterModel goes into EditorTemplates/UserListFilterModel.ascx.
And then add it as a property on my view model for the page.
public class MyPageViewModel
{
public UserListFilterModel Filter { get; set; }
}
Then I add the filter model to the model for the page and displays it like this:
<%= Html.EditorFor(x => x.Filter)%>
You are probably wrapping the filter in a form to allow the user to submit the values so I think it belongs in EditorTemplates. The users is in fact editing the filter model.
(If you really want to separate them ing you could use the UIHintAttribute but I wouldn't)
Edit: I added some sample code.
I think you misunderstand how Templates work. Templates do not make sense in the context you are describing.
Templates work on a SINGLE data item (although that data item can contain multiple data items, which in turn have their own templates).
The concept of a Filter is to control multiple data items, thus they do not map well to a template.
What you could do is create a DisplayTemplate for your collection class that adds filtering, thus no need to create a custom type of template. Just use DisplayTemplates.

How to avoid needing a VIewModel for every Model

I'm using ASP.NET 4 and MVC3.
Often, I find that I need a ViewModel to display information for my Model. For example, take the following model
class Profile
{
public int UserID { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
}
There is a requirement to hide the UserID, but to show the UserName, so often time for models that are similar to the one above, I have to come up with a ViewModel with just the UserID changed to UserName:
class ProfileViewModel
{
public string UserName { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
}
Are there any ways?
Until recently I always passed my models to my action methods as I also thought that creating viewModels with the same property names was duplication (its not). This caused me a lot of pain. I have now been re-educated and almost always use viewModels exclusively in my action methods (of course there will always be situations were it is fine to pass the model directly to the action method).
Have a read of this post which is the one that converted me to using viewModels. This will tell you the following:
The difference between models and viewModels
When each should be used.
How to avoid some security issues with the default model binder.
On top of the information in the linked post you should also consider things such as validation. I had a model that implemented the IValidateableObject interface to ensure the entity was in a valid state before being saved to the database.
In my ASP.NET application I wanted to create a multi-step form that allowed the user to enter the information over a number of pages. The problem I had here was that ASP.NET also uses the IValidatableObject interface during the model binding process.
If you are only allowing the user to enter a subset of the information required for the entity, the model binder will only be able to fill in the information that was given. Depending on how complex your validation is, this can result in the ModelState being marked as invalid as the entire entity is not valid.
The way I got around this was to have a viewModel representing each step each with its own validation. This way you are only validating the properties at each step. Once you get to the final step and everything is valid, I create an appropriate entity using the information given by the user. This entity will only have database-level validation checks performed upon it (field lengths etc.)
My suggestion is not to avoid viewModels but to understand why they are used and embrace them.
No, there isn't, once a member is public, it's public. Now, if the UserID property was internal, then you wouldn't have that problem.
However, one of the aims of MVVM here is to encapsulate logic regarding the interaction of the model and the view. Even if you have the view model and model in separate assemblies and make the UserID property internal, you should still have a view model; if changes come down the line where more functionality is required than simply binding to the model, you are prepared.
Direct access to the model is always a no no.
Additionally, if you really wanted, you could always use T4 templates to auto-generate the code for you (you could use Code DOM on the original CS file) to output your view models for you.
I usually have multiple ViewModels per model - the tradeoff you have to make comes down to this:
Are you comfortable coupling business logic (data annotations, display information, etc...) with your (persistence) models?
Are you comfortable doing all of the hide / display business logic purely within the View and not use the Controller + scaffolding to make those decisions for you?
The downside of creating all of those ViewModels of course is sub-class explosion, but the right way to think about it is in terms of the questions I listed IMHO.

Resources