First option in Blazor InputSelect displayed but value is null - asp.net-core

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>

Related

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.

Spinner does not show b/c the bound variable is not updated

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();
}

Struggling with the razor select helper

While trying out ASP.NET Core 2.2 MVC with razor, I had a hell of a struggle with this, and I'm still not sure why my prior attempts -- which I thought mimicked what I saw here on stackoverflow -- did not display the selected option, but here's one magic potion that does:
In vwProjectViewModel I have:
public List<SelectListItem> PageNumbers { get; set; }
public int PageNumber { get; set; }
Here's the cshtml view snippet:
#model vwProjectViewModel
<select name="PageNumber" id="PageNumber"
asp-items='new SelectList(#Model.PageNumbers,
"Value", "Text",
Model.PageNumber)'>
</select>
Here's a question: Why does adding asp-for="PageNumber" to the select tag break it so carelessly, making it no longer display the selected option?
Also, why does this simple syntax not display the selected option (didn't I see this here?):
<select asp-for="PageNumber" asp-items="#Model.PageNumbers"></select>
or
<select asp-for="PageNumber" asp-items="Model.PageNumbers"></select>
This also seems to display the selected option, but is considerably less elegant:
<select name="PageNumber" id="PageNumber">
#{
#foreach (SelectListItem #item in #Model.PageNumbers)
{
#if (#Model.PageNumber.ToString() == #item.Value)
{
<option value="#item.Value" selected="selected">#item.Text</option>
}
else
{
<option value="#item.Value" >#item.Text</option>
}
}
}
</select>
Anyone care to shed some light on this quirky tag helper?
<select id="PageNumber" asp-for="PageNumber" asp-items="Model.PageNumbers"> </select>
It will set selected if the value of PageNumber if it has one that matches the value of a SelectListItem:
List<SelectListItem> selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem() { Value = "1", Text = "1" });
selectListItems.Add(new SelectListItem() { Value = "2", Text = "2" });
And :
vwProjectViewModel mymodel = new vwProjectViewModel();
mymodel.PageNumbers = new List<SelectListItem>();
mymodel.PageNumbers = selectListItems;
mymodel.PageNumber = 2;

.NET Core new SelectList returns null

I am writing a .netcore webapp and I am using globalization to populate a list of countries this is in my controller class:
public IActionResult GetCountry()
{
List<string> CountryList = new List<string>();
CultureInfo[] cInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
foreach (CultureInfo cInfo in cInfoList)
{
RegionInfo r = new RegionInfo(cInfo.LCID);
if(!(CountryList.Contains(r.EnglishName)))
{
CountryList.Add(r.EnglishName);
}
}
//sort list into order
CountryList.Sort();
ViewBag.CountryList = CountryList;
return View(CountryList);
}
I have the following in my model class:
[Display(Name ="Country of Origin")]
public string GetCountry { get; set; }
and finally in my cshtml I have the following:
<div class="form-group">
<label asp-for="GetCountry"></label>
<select asp-for="GetCountry" asp-items="new SelectList(ViewBag.CountryList)"></select>
</div>
I am not sure where I have gone wrong but it will give me the following message during runtime.
ArgumentNullException: Value cannot be null.
Parameter name: items
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField)
I've probably done something silly but any help will be appreciated.
You missed # in asp-items
<div class="form-group">
<label asp-for="GetCountry"></label>
<select asp-for="GetCountry" asp-items="#(new SelectList(ViewBag.CountryList))"></select>
</div>
The code that you are using, does correctly populate the list of cultures.
It's more than likely that your .cshtml file is not populated with the correct view model.
At the top of the page, you'd normally see something like:
#model MyApplication.Models.Country.CountryListModel;
ViewBag.CountryList = Model.CountryList;

mvc passing parameter to controller

I am very new to MVC
I need some help to over come the issue of passing parameter to a controller on form submit
what i have got is the following controller and the view
public ActionResult Index(string method ="None")
{
if (Request.HttpMethod == "POST")
{
switch (method)
{
case "Add10":
_bag.GetBag = Get100Products().Take(10).ToList<Product>();
break;
case "Clear":
_bag = null;
_bag.GetBag = null;
_bag = new Models.Bag();
break;
case "Add":
if ((Request.Form["Id"] != null) && (Request.Form["Id"] != ""))
{
if (_bag.GetBag.Count < 100)
{
var p = GetProduct(Request.Form["Id"]);
int qnt = Convert.ToInt16(Request.Form["qnt"]);
if (p.ItemNumber != null)
{
p.Quantity = qnt;
p.Index++;
_bag.Item = p;
}
}
}
break;
}
}
return View(_bag.GetBag);
}
and the view part of the view
<div style="vertical-align:middle">
#using (Html.BeginForm("", "Home", new { method = "Add10" }, FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Add 10 Items to bag" />
}
#using (Html.BeginForm("GetDiscount", "Home", FormMethod.Post))
{
<div>
<!-- form goes here -->
<input type="submit" value="Get Discount" />
With MAX time in seconds <input type="text" name="time" maxlength="2" value="2" />
</div>
}
#using (Html.BeginForm("", "Home", new { method = "Clear" }, FormMethod.Post))
{
<input type="submit" value="Empty the bag" />
}
</div>
so i am expecting when the use clicked button Add 10 Items to bag to pass the method value "Add10" to the index controller and when clicked Empty the bag to pass "Clear" the method value in index controller
but it always shows as "None"
what have I done wrong?
</form>
First of all, you have to add [HttpPost] to your controller in order to accept POST requests:
[HttpPost]
public ActionResult Index(string method ="None")
{
You should differentiate GET and POST actions.
You can do like this:
// [HttpGet] by default
public ActionResult Index(Bag bag = null)
{
// "bag" is by default null, it only has a value when called from IndexPOST action.
return View(bag);
}
[HttpPost]
public ActionResult Index(string method)
{
// Your logic as specified in your question
return Index(_bag.GetBag);
}
EDIT:
Your code is wrong, for example you will get a NullReferenceException because your try to call a property on a null object (_bag):
_bag = null;
_bag.GetBag = null; // NullReferenceException: _bag is null!
Also your code would be cleaner and more easier to maintain if we split this Action into several actions and follow the technology philosophy.
Do you consider refactoring this piece of code into smaller and more understandable chunks?