Validation messages from custom model validation attributes are locked to first loaded language - asp.net-mvc-4

I am working on a multi lingual website using Umbraco 7.2.4 (.NET MVC 4.5). I have pages for each language nested under home nodes with their own culture:
Home (language selection)
nl-BE
some page
some other page
my form page
fr-BE
some page
some other page
my form page
The form model is decorated with validation attributes that I needed to translate for each language. I found a Github project, Umbraco Validation Attributes that extends decoration attributes to retrieve validation messages from Umbraco dictionary items. It works fine for page content but not validation messages.
The issue
land on nl-BE/form
field labels are shown in dutch (nl-BE)
submit invalid form
validation messages are shown in dutch (nl-BE culture)
browse to fr-BE/form
field labels are shown in french (fr-BE)
submit invalid form
Expected behavior is: validation messages are shown in french (fr-BE culture)
Actual behavior is: messages are still shown in dutch (data-val-required attribute is in dutch in the source of the page)
Investigation to date
This is not a browser cache issue, it is reproducible across separate browsers, even separate computers: whoever is generating the form for the first time will lock the validation message culture. The only way to change the language of the validation messages is to recycle the Application Pool.
I doubt that the Umbraco Validation helper class is the issue here but I'm out of ideas, so any insight is appreciated.
Source code
Model
public class MyFormViewModel : RenderModel
{
public class PersonalDetails
{
[UmbracoDisplayName("FORMS_FIRST_NAME")]
[UmbracoRequired("FORMS_FIELD_REQUIRED_ERROR")]
public String FirstName { get; set; }
}
}
View
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
var model = new MyFormViewModel();
using (Html.BeginUmbracoForm<MyFormController>("SubmitMyForm", null, new {id = "my-form"}))
{
<h3>#LanguageHelper.GetDictionaryItem("FORMS_HEADER_PERSONAL_DETAILS")</h3>
<div class="field-wrapper">
#Html.LabelFor(m => model.PersonalDetails.FirstName)
<div class="input-wrapper">
#Html.TextBoxFor(m => model.PersonalDetails.FirstName)
#Html.ValidationMessageFor(m => model.PersonalDetails.FirstName)
</div>
</div>
note: I have used the native MVC Html.BeginForm method as well, same results.
Controller
public ActionResult SubmitFranchiseApplication(FranchiseFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
TempData["Message"] = LanguageHelper.GetDictionaryItem("FORMS_VALIDATION_FAILED_MESSAGE");
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
TempData["Message"] += "<br/>" + error.ErrorMessage;
}
}
return RedirectToCurrentUmbracoPage();
}
}
LanguageHelper
public class LanguageHelper
{
public static string CurrentCulture
{
get
{
return UmbracoContext.Current.PublishedContentRequest.Culture.ToString();
// I also tried using the thread culture
return System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
}
}
public static string GetDictionaryItem(string key)
{
var value = library.GetDictionaryItem(key);
return string.IsNullOrEmpty(value) ? key : value;
}
}

So I finally found a workaround. In attempt to reduce my app to its simplest form and debug it, I ended up recreating the "UmbracoRequired" decoration attribute. The issue appeared when ErrorMessage was set in the Constructor rather than in the GetValidationRules method. It seems that MVC is caching the result of the constructor rather than invoking it again every time the form is loaded. Adding a dynamic property to the UmbracoRequired class for ErrorMessage also works.
Here's how my custom class looks like in the end.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
AllowMultiple = false)]
internal class LocalisedRequiredAttribute : RequiredAttribute, IClientValidatable
{
private string _dictionaryKey;
public LocalisedRequiredAttribute(string dictionaryKey)
{
_dictionaryKey = dictionaryKey;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
ErrorMessage = LanguageHelper.GetDictionaryItem(_dictionaryKey); // this needs to be set here in order to refresh the translation every time
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage, // if you invoke the LanguageHelper here, the result gets cached and you're locked to the current language
ValidationType = "required"
};
}
}

Related

Identify which MudExpansionPanel is being expanded

I want to present a list of up to 20 panels within a <MudExpansionPanels> component where the expanded child portion of each <MudExpansionPanel> is expensive to render. I tried the following test code but all instances of <LiveAgentSummary> are rendered as the parent is rendered, just to clarify this rendering of <LiveAgentSummary> happens before any panel is manually expanded.
<MudExpansionPanels>
#foreach (var liveAgent in _liveAgents)
{
<MudExpansionPanel Text=#liveAgent.Name>
<LiveAgentSummary AgentId=#liveAgent.Id />
</MudExpansionPanel>
}
</MudExpansionPanels>
I then looked into delaying the render of each <LiveAgentSummary> through use of a RenderFragment that is dynamically built during the <MudExpansionPanel> IsExpandedChanged event. However the event handler does not indicate which panel is being expanded and hence I do not know which liveAgent.Id param value to pass to <LiveAgentSummary> as I build a RenderFragment.
I think <MudExpansionPanels> is missing support for a bind-ActivePanelId property but hopefully I am overlooking an alternative solution to my delayed rendering objective.
This is the official MudBlazor example that prompted me to look into using a RenderFragment.
Update: A long answer briefly appeared yesterday suggesting that I could query the list of panel components on a built-in property that indicates the expanded state. The poster had gone to the trouble of reading the MudBlazor source code but the answer was then deleted.
I am now wondering how from code in an event handler it is possible to iterate over a component hierarchy declared as mark-up. Applying this to my example markup above, how could event handler code obtain a reference to each <MudExpansionPanel> child within <MudExpansionPanels>.
Can't you make use of the bool from the IsExpandedChanged callback? Something like this:
Index.razor
#page "/"
<MudExpansionPanels>
#foreach (var liveAgent in this.liveAgents)
{
<MudExpansionPanel
Text="#($"{liveAgent.Name} ({liveAgent.Data})")"
IsExpandedChanged="#(e => this.Load(e, liveAgent))">
<LiveAgentSummary Agent="#liveAgent" />
</MudExpansionPanel>
}
</MudExpansionPanels>
#code {
private readonly List<Agent> liveAgents = new()
{
new Agent("1", "Agent Smith"),
new Agent("2", "Agent Brown"),
new Agent("3", "Agent Jones")
};
private void Load(bool expanded, Agent agent)
{
if (expanded)
{
agent.Load();
}
}
}
LiveAgentSummary.razor
<MudText>id: #this.Agent.Id, data: #this.Agent.Data</MudText>
#code {
[Parameter]
public Agent Agent { get; set; } = default!;
}
Agent.cs
public record Agent(string Id, string Name)
{
public string Data { get; set; } = "Not loaded";
public void Load()
{
Console.WriteLine($"Loading agent {this.Id}...");
this.Data = "Loaded!";
}
}

Loding pages by posting parameters

The subject might not be clear since I couldn't find a better way to express it.
I am developing a web application using ASP.NET Core 6.0 with Razor Pages. Our previous application was an SPA using Ext JS where any call to server was returning only data and where I was also able to make any kind of call (GET/POST) to get the data.
For example, in the above picture from my old application, I make an ajax call with POST to get the list of periods when I open this page. I make a POST because I am sending the period type in my request payload. Sure I can pass these parameters in a GET request, however my other views have many criteria, so passing these criteria in the query string is not what I want. So, I decided to make it a standard to make my calls with POST method if there are any criteria payload, make GET request only when fething an entity with a simple key parameter (like Id) or GET any list that doesn't have any criteria.
Now, I am quite confused how to do same thing in my new ASP.NET Core Razor Pages web application. Normally, the menu items navigate to the page using link as below, which makes a GET request:
<a asp-area="System" asp-page="/ProfessionList">#AppLocalizer["Profession List"]</a>
<a asp-area="System" asp-page="/PeriodList">#AppLocalizer["Profession List"]</a>
In order to make a POST request, I replaced the menu item for period list as following which makes a POST request with a default periodType payload:
<a asp-area="System" asp-page="/ProfessionList">#AppLocalizer["Profession List"]</a>
<form asp-area="System" asp-page="/PeriodList" method="post">
<input type="hidden" name="periodType" value="1" hidden />
<button type="submit" >#AppLocalizer["Period List"]</button>
</form>
And the corresponding PeriodType.cshtml.cs file is as following:
[Authorize]
public class PeriodListModel: BaseEntityListPageModel<List<JsonPeriodEx>> {
public PeriodListModel(ILogger<BaseEntityListPageModel<List<JsonPeriodEx>>> logger, WebApi webApi) : base(logger, webApi) {
}
public IActionResult OnGet() {
PageData = JsonConvert.DeserializeObject<List<JsonPeriodEx>>(TempData["PageData"].ToString());
return Page();
}
public async Task<IActionResult> OnPostAsync(int periodType) {
var jsonResult = await _WebApi.DoPostAsync<List<JsonPeriodEx>>("/PeriodEx/GetList", new[] { new { Property = "periodType", Value = periodType } });
if (jsonResult.IsLoggedOut)
return RedirectToPage("/Login", new { area = "Account" });
if (jsonResult.Success) {
PageData = jsonResult.Data;
TempData["PageData"] = JsonConvert.SerializeObject(PageData);
return RedirectToPage("/PeriodList");
} else {
return RedirectToPage("/Error");
}
}
}
OnPostAsync successfully binds to the posted periodType parameter and gets the list of periods. Now, at the end of a successful call I want to follow the Post/Redirect/Get pattern and redirect to OnGet with the data from OnPostAsync, which is stored in TempData.
Now, according to the above scenario, is my approach, explained above, correct or should I implement it differently?
Thanks in advance
For these cases I would prefer TempData. Much easier and less code.
public async Task OnGet()
{
TempData["myParamToPass"] = 999;
...
}
public async Task OnPostReadData()
{
if (TempData.ContainsKey("myParamToPass"))
{
var myParamToPassValue = TempData.Peek("myParamToPass") as int?;
...
}
...
}

What is difference between Page() and Rediirect() to self in ASP.NET Core Razor pages?

I have a very simple page that has 2 forms. When I submit one form it resets the other. There is some kind of hidden optimization is going on because when I refresh the page it presents the correct result.
Here is the page:
<div asp-validation-summary="All"></div>
<div class="col-md-3">
<form method="POST">
<fieldset>
<div>Host Name: <input asp-for="ClientConfig.HostName" /></div>
<div>Responses in HTML? <input type="checkbox" asp-for="ClientConfig.Html" /></div>
<input type="submit" asp-page-handler="ClientConfiguration" />
</fieldset>
</form>
<p>Base URL = #Model.ClientConfig.Summary</p>
</div>
<form method="POST">
<fieldset>
<div>Name: <input asp-for="Customer.Name" /></div>
<div>New? <input type="checkbox" asp-for="Customer.New" /></div>
<input type="submit" asp-page-handler="Customer" />
</fieldset>
</form>
<ul>
<li>Customer = #Model.Customer.Summary</li>
</ul>
Here is the model...
public class ClientConfig
{
public static ClientConfig Instance { get; set; } = new ClientConfig();
[Required, StringLength(100)] public string HostName { get; set; } = "LocalHost";
public bool Html { get; set; }
public string Summary => HostName + (Html ? " (Html)" : "");
}
public class Customer
{
public static Customer Instance { get; set; } = new Customer();
[Required, StringLength(100)] public string Name { get; set; } = "Default";
public bool New { get; set; }
public string Summary => Name + (New ? " (New)" : "");
}
public class IndexModel : PageModel
{
public IndexModel()
{
ClientConfig = ClientConfig.Instance;
Customer = Customer.Instance;
}
[BindProperty] public ClientConfig ClientConfig { get; set; }
[BindProperty] public Customer Customer { get; set; }
public async Task<IActionResult> OnPostCustomerAsync()
{
Customer.Instance = Customer;
return Page();
}
public async Task<IActionResult> OnPostClientConfigurationAsync()
{
ClientConfig.Instance = ClientConfig;
return Page();
}
}
So what is "return Page();" doing? According to the documentation it is simply rendering the current page. Not true. To verify this, simply refresh the page. It will be different, accurate with both forms filled in. Also if you replace "return Page()" with "return Redirect("/Index");" the result will also be accurate. So again, what is "return Page()" doing? There is some kind of undocumented optimization that resets all the forms except the one recently submitted.
You have multiple separate forms on your page with separate form values: In one form you are submitting the client configuration object, in the other you are submitting the customer object.
So when you are actually submitting a form, only that form's data is being submitted. For example, if you are submitting the customer form, the client configuration data is not being transferred in the POST request (and the other way around).
As such, when you render the page by returning Page(), only the data that is currently in the page model is being rendered. If you are submitting the customer form, then only the customer data is available (same for the client configuration form).
This happens simply because you only have partial data on a page where you would need more to fill in all forms. If you want to prevent that, you will have to combine the data into a single model and form.
Now, if you refresh the page in the browser, then your browser is typically smart enough not to clear form values immediately. If you do a hard refresh using Ctrl + F5, then the browser should also reset the values.
It's also possible that your browser is performing an auto-fill for the forms here. This will typically only apply for GET requests. So that could be the reason why you are getting this result when you return a Redirect() because that completes the form POST with a GET request.
When I submit one form it resets the other.
That's the expected behavior for the way you coded your page. When the form POSTs to the server, the server does three things:
creates a new IndexModel object using its constructor,
binds the object's properties to the POSTed form values, and
binds the object to its view.
In your code, step (1) resets properties to their default values. Step (2) overwrites those defaults with POSTed form values. Since you're submitting only one form, the other form's values retain their defaults. That's why submitting one resets the other.
So what is "return Page();" doing? According to the documentation it is simply rendering the current page. Not true. To verify this, simply refresh the page. It will be different, accurate with both forms filled in. Also if you replace "return Page()" with "return Redirect("/Index");" the result will also be accurate.
When you submit a form, return Page() renders the page in the context of a POST. On the other hand, when you refresh or redirect, the context is a GET. The difference you see happens because the context is different: the response to a POST is different from the response to a GET.
Right. After quite a long time of pondering this problem, I've finally figured it out. The problem: Razor pages moves in mysterious ways its wonders to perform.
My initial assumption was wrong. The page model constructor is not being bypassed. The page model is being properly constructed from static values. However after construction all bound objects on the page are reset. So this is not an "undocumented optimization"...it is an undocumented impairment.
The fix for this is to reset the page model from static values before returning Page().
public async Task<IActionResult> OnPostCustomerAsync()
{
Customer.Instance = Customer;
ClientConfig = ClientConfig.Instance;
return Page();
}
public async Task<IActionResult> OnPostClientConfigurationAsync()
{
ClientConfig.Instance = ClientConfig;
Customer = Customer.Instance;
return Page();
}
This is obviously a massive kluge, but no elegant solution exists. Anyone?

Variable number of HttpPostedFileBase objects

Currently, I have this:
public ActionResult Add(FormCollection form, HttpPostedFileBase fr, HttpPostedFileBase en, HttpPostedFileBase es)
{
Upload(fr, "fr");
Upload(en, "en");
Upload(es, "es");
...
}
This works for what we're doing currently, but just learned of a new requirement where the system needs the ability to add other languages. This is the only part where I have an issue.
I tried:
public ActionResult Add(FormCollection form, HttpPostedFileBase[] fr)
{
foreach(var file in fr)
{
Upload(file, "I'mStuck");
}
...
}
as a test, but it will only have 1 element and it is the one where id/name = fr. Makes sense, but not particularly helpful for what I need.
I could do:
for (string file in Request.Files)
{
...
}
which would handle the upload component fine, but the issue is that unless I can force them to standardize against a whatever_langabbreviation.extension file format, which I can't, I'm not going to be able to know what the language abbreviation is.
How can I obtain the id/name fields for the input type=file objects within the controller?
I was actually incorrect. The string returned is actually the id or name (think name, but considering I typically pair id/name, it works).
For the controller that renders the view initially, I did:
List<Languages> langs = db.Languages.ToList();
viewmodel.Languages = langs;
return View(viewmodel);
In the view itself:
foreach(Language lang in Model.Languages)
{
// Label
<input type="file" id="#lang.Abbreviation" name="#lang.Abbreviation" />
}
And in the post event:
foreach(string file in Request.Files)
{
HttpPostedFileBase fb = Request.Files[file];
Upload(fb, file);
}
And it handles as it is supposed to (Upload being a function that just adds a new item to another table.

How to display validation exceptions received from WCF service in MVC3 app

I have a MVC3 app that uses WCF services for data access. WCF services uses EF4.1 for data access.
I want minimum dependencies between MVC3 app and WCF services, so they don't share any libraries. The only dependency in MVC3 app is the service reference.
To validate entities on save, I defined the operation contracts on WCF services to generate FaultContract defined as below:
[OperationContract]
[FaultContract(typeof(EntityFault))]
void AddAddressEntity(Address entity);
EntityFault is defined as below:
[DataContract(IsReference=true)]
public class EntityFault
{
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public virtual ICollection<ValidationErrorMessage> ValidationErrorMessages
{ get; set; }
}
and ValidationErrorMessage is a simple class with two properties, PropertyName and ValidationMessage
I trap DbEntityValidationException as below:
try
{ //....
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
EntityFault ef = EntityFaultHelper.CreateValidationFault(ex, entity);
throw new FaultException<EntityFault>(ef, ef.ErrorMessage);
}
In my MCV3 app I intercept the fault exception. But how can I display the error messages either in
#Html.ValidationMessageFor(<my specific field>)
or in
#Html.ValidationSummary(...)
section?
If the model fields were annotated, or if the client entity implements IValidatableObject, error msgs are displayed in specified areas.
One idea is to use ViewBag, and define display placeholders for error msgs received from WCF's FaultContract, and set the corresponding ViewPag dinamic properties for received error msgs.
But I'm wondering if there's a better approach.
Thanks
So far I found the following solution
I added for each field in the view a placeholder to display error message as below:
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.State)
#ViewBag.StateError
</div>
Then in the controller I have this code
using (var addressClient = new AddressServiceClient(_configName))
{
try
{
addressClient.AddAddressEntity(address);
return RedirectToAction("Index");
}
catch (FaultException<EntityFault> ex)
{
foreach (var err in ex.Detail.ValidationErrorMessages)
{
ViewData.Add(
string.Format("{0}Error", err.PropertyName),
err.ErrorMessage);
}
}
}
And it display the errors right next to fields.
But I'm still wondering if there's a way to use the placeholders
#Html.ValidationMessageFor(model => model.Address1)
or
#Html.ValidationSummary(true)
The reason is, I don't want to have to manually change all the Create / Edit views generated by MVC3 VS helper, I prefer to find a way to reuse those placeholders.
Edit
I found a better solution. It works directly with the view generated by MVC out of the box.
The key code is to set the error messages in ModelState as below
try
{
addressClient.AddAddressEntity(address);
return RedirectToAction("Index");
}
catch (FaultException<EntityFault> ex)
{
foreach (var err in ex.Detail.ValidationErrorMessages)
this.ModelState.AddModelError(err.PropertyName, err.ErrorMessage);
}
The point is in ModelState there is a key for each model field (property), with property name as key. So by adding model error for that property, the error message is displayed in the corresponding place for validation error