Spinner does not show b/c the bound variable is not updated - asp.net-core

I'm working on a Blazor server side app. The page has a table with a list of cars and some filter elements on top. When I select a filter, a spinner should be visible until the new data is fetched and rendered.
The spinner with its variable:
<div class="spinner-border #spinner" role="status">
<span class="visually-hidden">Loading...</span>
</div>
#code{
string spinner = "invisible";
public string vehicleTypeFilter
{
set
{
_vehicleTypeFilter = value;
ApplyFilters();
}
get { return _vehicleTypeFilter; }
}
}
The select for the Baumuster (vehicleType) is bound to the vehicleTypeFilter variable:
<div class="col-md-2 form-floating">
<select class="form-control" #bind="vehicleTypeFilter">
<option value="" selected>Alle</option>
#foreach (var vehicleType in vehicleTypes.OrderBy(x => x.Description))
{
<option value="#vehicleType.Description">#vehicleType.Description</option>
}
</select>
<label>Baumuster</label>
</div>
Then a value is selected, the ApplyFilter method is triggered through the setter of the vehicleTypeFilter variable:
public void ApplyFilters()
{
ToggleSpinner();
// I also tried a StateHasChanged(); right here
// 1. Get all cars
cars = model.CreateIndexViewModel();
// 2. Filter for Baumuster / vehicle type
if (!string.IsNullOrEmpty(vehicleTypeFilter))
{
cars.viewModels = cars.viewModels.Where(x => x.VehicleDescription == vehicleTypeFilter).ToList();
}
ToggleSpinner();
}
The ToggleSpinner method:
public void ToggleSpinner()
{
if (spinner == "invisible" )
spinner = "";
else
spinner = "invisible";
}
Unfortunately, I don't see the spinner. When I inspect the html page right after the breakpoint hits the Baumuster-filter, the value of spinner is still set to "invisible". I even tried to call StateHasChanged(); after the first ToggleSpinner() but that didn't help.

You've shown a lot of code, but I don't see ToggleSpinner
However, you call it twice in your ApplyFilters method, with no blocking calls, so I'd assume that it's turning the spinner on and off so fast that it doesn't render (or at least that you can't notice it).
If the methods you call in ApplyFilters actually take any time, then Henk's got the right idea-- except you should use async Task I think.

Your problem is that you want async behaviour from a synchronous property. The standard advice is against async void but if you want to stay with the property, the minimal change would be:
public async void ApplyFilters()
{
ToggleSpinner();
// I also tried a StateHasChanged(); right here
StateHasChanged(); // this _requests_ an update
await Task.Delay(1); // this is why you need async void
... as before
ToggleSpinner();
StateHasChanged();
}

Related

Wait a task to finish in Blazor WASM

Please tell me :
How can I wait a task until it is finished in Blazor WASM, no matter the time it takes to complete ?
My UserInfoService.GetUserBasicInfoToListAsync() task through an API controller gets some data from a server SQL table.
Thank You !
protected override async Task OnInitializedAsync()
{
await UserInfoService.GetUserBasicInfoToListAsync().ConfigureAwait(false);
//here must wait the previous task to complete
if (UserInfoService.UserBasicInfoList.Count > 0)
{ //do some code}
}
I think what you're looking for is something like this: I'm assuming your problem is the UI rendering before the async call is complete. [But I may be wrong!]
#page "/"
<PageTitle>Index</PageTitle>
#if (loaded)
{
<div class="bg-dark text-white p-2 m-2">
Rows Retrieved: #NoOfRows
</div>
}
else
{
<div class="alert alert-warning">Loading Records to find the number</div>
}
#code {
private bool loaded;
private int NoOfRows = 0;
protected override async Task OnInitializedAsync()
{
// Task Delay to emulate a slow async call into the data pipeline
// replace with your await
await Task.Delay(3000);
// await UserInfoService.GetUserBasicInfoToListAsync()
NoOfRows = Random.Shared.Next(1, 10);
loaded = true;
}
}

Could not set or bind model property with Bootstrap Datepicker in Blazor

I am using bootstrap datepicker and the problem is that when I pick a date, it does not fire a change or input event and noting is binding with the model property Course.StartDate or Course.EndDate.
The default datepicker works but does not support Afghanistan datetime. That is why I use boostrap datepicker.
Blazor code:
#using Microsoft.AspNetCore.Mvc.Rendering
#using myproject.Data
#using Microsoft.JSInterop;
#inject myproject.Repository.CoursesRepository _coursesRepository
#inject IJSRuntime JS
<EditForm Model="#Course" OnValidSubmit="e=> { if(selectedId == 0) { addCourse(); } else { updateCourse(Course.CourseId); } }">
<div class="mb-2">
<div>#Course.StartDate</div>
<label class="col-form-label" for="StartDate">#Loc["Start Date"]<span class="text-danger fs--1">*</span>:</label>
<InputDate class="form-control" #bind-Value="Course.StartDate" #bind-Value:format="yyyy-MM-dd" id="StartDate" />
<ValidationMessage class="text-danger" For="(() => Course.StartDate)"/>
</div>
<div class="mb-2">
<label class="col-form-label" for="EndDate">#Loc["End Date"]<span class="text-danger fs--1">*</span>:</label>
<InputDate class="form-control" #bind-Value="Course.EndDate" #bind-Value:format="yyyy-MM-dd" id="EndDate"/>
<ValidationMessage class="text-danger" For="(() => Course.EndDate)"/>
</div>
</EditForm>
#code {
public CourseModel Course = new();
public string[] dates = new string[] { "#StartDate", "#EndDate" };
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
loadScripts();
}
void addCourse()
{
_coursesRepository.AddCourse(Course);
FillData();
Course = new();
var title = "Course";
Swal.Success(title : Loc[$"{title} added successfully"],toast : true);
}
// initializes the datepicker
public async Task loadScripts()
{
await JS.InvokeVoidAsync("initializeDatepicker", (object) dates);
}
}
This is script for initializing the datepickers
<script>
function initializeDatepicker(dates) {
dates.forEach((element) => {
$(element).datepicker({
onSelect: function(dateText) {
// this is not working
element.value = this.value;
/*
tried this and still not working
$(element).trigger("change");
also tried this and still not working
$(element).change();
*/
// this is working
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
},
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true
});
});
}
</script>
The reason for this is that the changes are made with JavaScript and so the page state does not change for Blazor, in other words, Blazor does not notice the value change at all.
To solve this problem, you must inform the Blazor component of the changes by calling a C# method inside the JavaScript function. For this, you can use the DotNet.invokeMethodAsync built-in dotnet method. As follows:
DotNet.invokeMethodAsync('ProjectAssemblyName', 'ComponentMethod', this.value.toString())
Its first argument is the assembly name of your project. The second argument is the name of the C# function that you will write in the component, and finally, the third argument is the selected date value.
The method called in C# should be as follows:
static string selectedDate;
[JSInvokable]
public static void ComponentMethod(string pdate)
{
selectedDate = pdate;
}
This method must be decorated with [JSInvokable] and must be static.
I have done the same thing for another javascript calendar in Persian language. Its codes are available in the JavaScriptPersianDatePickerBlazor repository.
You can also create a custom calendar in the form of a component so that you can use it more easily in all components in any formats that you want such as DateTime or DateTimeOffset or string and so on. There is an example of this in the AmibDatePickerBlazorComponent repository.

First option in Blazor InputSelect displayed but value is null

I have encountered a weird behavior of InputSelect element in Razor component.
On my input form, I have several fields bound with the model (Partner). Some of these fields I placed in form of dropdown selection. Because the bound field's (PartnerCategory) value is the id (integer) I fetch a lookup table from DB with a name corresponding to a selected id.
On a page, I can see all names in the dropdown list. But when I try to insert a record from the form to the database it throws an SQL exception, because InputSelect treats the first value in the list as NULL. Just to be clear - there is no blank value in the dropdown list, and all names are shown. It just takes it's value as NULL. Followingly because the data type is an integer and it converts NULL to zero. And because I don't have an id that is zero in my table, the Insert command fails.
Below is my simplified code
<EditForm Model="#partner">
<InputSelect #bind-Value="partner.PartnerCategoryId">
#if (categoryList != null)
{
#foreach (var item in categoryList.OrderBy(x => x.PartnerCategoryId))
{
<option value="#item.PartnerCategoryId">#item.Name</option>
}
}
</InputSelect>
</EditForm>
#code {
Partner partner = new Partner();
private IEnumerable<PartnerCategory> categoryList;
protected override async Task OnInitializedAsync()
{
categoryList = await CategoryService.GetAllAsync();
}
}
How can I handle this? Does it bind values to a model before it fetches data from DB?
To solve this issue you can add <option value="">Select...</option> in your code like this:
<InputSelect #bind-Value="partner.PartnerCategoryId">
#if (categoryList != null)
{
<option value="">Select...</option>
#foreach (var item in categoryList.OrderBy(x => x.PartnerCategoryId))
{
<option value="#item.PartnerCategoryId">#item.Name</option>
}
}
</InputSelect>
And in your PartnerCategory model define the PartnerCategoryId as required. Note that the type of PartnerCategoryId is nullable: int?
[Required]
public int? PartnerCategoryId {get; set;}
This will prevent the 'submission' of your form unless the user has selected a value
To test the new changes:
Add the OnValidSubmit attribute to your EditForm component and set its value to "HandleValidSubmit"
Add a HandleValidSubmit method, like this:
private void HandleValidSubmit()
{
// Put code here to save your record in the database
}
Add a submit button at the bottom of your EditForm:
<p><button type="submit">Submit</button></p>
Run your app, and hit the "Submit" button...As you can see the form is not "submitted", and the select element's borders are painted red.
Here's a complete version of your code:
<EditForm Model="#partner" OnValidSubmit="HandleValidSubmit">
<InputSelect #bind-Value="partner.PartnerCategoryId">
#if (categoryList != null)
{
<option value="">Select...</option>
#foreach (var item in categoryList.OrderBy(x => x.PartnerCategoryId))
{
<option value="#item.PartnerCategoryId">#item.Name</option>
}
}
</InputSelect>
<p><button type="submit">Submit</button></p>
</EditForm>
#code {
Partner partner = new Partner();
private IEnumerable<PartnerCategory> categoryList;
protected override async Task OnInitializedAsync()
{
categoryList = await CategoryService.GetAllAsync();
}
private void HandleValidSubmit()
{
Console.WriteLine("Submitted");
}
}
In case someone is facing the same issue, here is my code which solved the issue:
<div class="mb-3 form-check">
<label for="category" class="form-label">Select category</label>
<InputSelect TValue="int" #bind-Value="subcategory.CategoryId" class="form-control" id="category">
<option value="">Select...</option>
#foreach(var cate in categories)
{
<option value="#cate.CategoryId">#cate.CategoryName</option>
}
</InputSelect>
<ValidationMessage For="#(()=>subcategory.CategoryId)"/>
</div>

Method that expands into tag-helper

I have the following method in a cshtml file. It simply expands into two label elements. The first is a plain label element. The second however, uses a tag helper:
async Task field(string str)
{
<label for="#str">#str</label>
<label asp-for="#str">#str</label>
}
Here's how I have it defined in the cshtml file along with calling it once:
#{
{
async Task field(string str)
{
<label for="#str">#str</label>
<label asp-for="#str">#str</label>
}
await field("abc");
}
}
If I 'view source' on the result, I see the following:
<label for="abc">abc</label>
<label for="str">abc</label>
Note that the #str argument was properly passed and used in the first case but was not in the second case. So it seems that there's an issue in passing the argument to the tag-helper variant here.
Any suggestions on how to resolve this?
In my opinion, the argument has been passed the tag-helper variant successfully. But the the label asp-for attribute will be rendered as the for attribute with asp-for ModelExpression's name value(str) not the value ModelExpression's model(abc).
According to the label taghelper source codes, you could find the tag helper will call the Generator.GenerateLabel method to generate the label tag html content.
The Generator.GenerateLabel has five parameters, the third parameter expression is used to generate the label's for attribute.
var tagBuilder = Generator.GenerateLabel(
ViewContext,
For.ModelExplorer,
For.Name,
labelText: null,
htmlAttributes: null);
If you want to show the str value for the for attribute, you should create a custom lable labeltaghelper.
More details, you could refer to below codes:
[HtmlTargetElement("label", Attributes = "asp-for")]
public class ExtendedAspForTagHelper:LabelTagHelper
{
public ExtendedAspForTagHelper(IHtmlGenerator generator)
: base(generator)
{
}
public override int Order => -10000;
//public override void Process(TagHelperContext context, TagHelperOutput output)
//{
// base.Process(context, output);
// if (!output.Attributes.TryGetAttribute("maxlength", out TagHelperAttribute maxLengthAttribute))
// {
// return;
// }
// var description = $"Only <b>{maxLengthAttribute.Value}</b> characters allowed!";
// output.PostElement.AppendHtml(description);
//}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
var tagBuilder = Generator.GenerateLabel(
ViewContext,
For.ModelExplorer,
For.Model.ToString(),
labelText: null,
htmlAttributes: null);
if (tagBuilder != null)
{
output.MergeAttributes(tagBuilder);
// Do not update the content if another tag helper targeting this element has already done so.
if (!output.IsContentModified)
{
// We check for whitespace to detect scenarios such as:
// <label for="Name">
// </label>
var childContent = await output.GetChildContentAsync();
if (childContent.IsEmptyOrWhiteSpace)
{
// Provide default label text (if any) since there was nothing useful in the Razor source.
if (tagBuilder.HasInnerHtml)
{
output.Content.SetHtmlContent(tagBuilder.InnerHtml);
}
}
else
{
output.Content.SetHtmlContent(childContent);
}
}
}
}
}
Improt this taghelper in _ViewImports.cshtml
#addTagHelper *,[yournamespace]
Result:

using MVC4 Strongly typed view with Knockout

I am trying to use knockout with MVC strongly typed view. Since my model will have over 20 properties, I prefer to use strongly-typed view model to post back data by using ko.mapping.toJS and ko.Util.postJson. The Eligible field was passed back correctly, however the following code does not post back the selected option from drop down list, it just showed value as 0 when I looked that selectOptionModel on the controller. Can someone point out what I did wrong?
the view model from server side is as follows:
public class SelectOptionModel
{
public bool Eligible { get; set; }
public int selectedOption { get; set; }
public IEnumerable<SelectListItem> AvailableOptions
{
get
{
return Enum.GetValues(typeof(OptionEnum)).Cast<OptionEnum>()
.Select(x => new SelectListItem
{
Text = x.ToString(),
Value = x.ToString()
});
}
}
}
public enum OptionEnum
{
[Description("First")]
FirstOption = 1,
[Description("Second")]
SecondOption = 2,
[Description("Third")]
ThirdOption = 3
}
The razor view is like following:
#model TestKo.Models.SelectOptionModel
...
subViewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
...
}
#using (Html.BeginForm()){
<button type="submit" class="button" id="SaveBtn">Save</button>
<div data-bind="with:vm">
<div>
#Html.LabelFor(model => model.Eligible)
#Html.CheckBoxFor(model => model.Eligible, new { data_bind = "checked: selectOptionVM.Eligible" })
</div>
<div>
#Html.LabelFor(model => model.selectedOption)
#Html.DropDownListFor(model => model.selectedOption, Model.AvailableOptions,
new
{ data_bind = "options: selectOptionVM.AvailableOptions, optionsText: 'Text', optionsValue: 'Value', value: selectOptionVM.selectedOption"
})
</div>
</div>
}
The javascript for the knockout view model is:
sectionVM = function (data) {
var self = this;
var selectOptionVM = data;
return {
selectOptionVM: selectOptionVM
}
}
$(document).ready(function () {
var viewModel = {
vm: new sectionVM(subViewModel)
};
ko.applyBindings(viewModel);
$("#SaveBtn").click(function () {
var optionModel = ko.toJS(viewModel.vm.selectOptionVM);
ko.utils.postJson($("form")[0], optionModel)
});
});
The controller part:
[HttpPost]
public ActionResult Create(SelectOptionModel selectOptionModel)
{
try
{
// TODO: Add insert logic here
var modelSaved = selectOptionModel;
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I'm venturing a bit of a guess here, but this could be the problem: the id-bit of your selected option will always be a string (because it will go in the <option value="" attribute). Your endpoint expects an int. As far as I can see, you don't convert the selectedOption before sending it to the server. try parseInt(selectedOption, 10) before sending it to the server. Also, use the network tool in your browser to debug the info that is being sent to the controller. That might help you to zone in on the problem.
Actually it works. Somehow it was not working previously, but after I cleared cache, cookies etc, it just worked. Thanks everyone!