Bootstrap Modal Popup using Blazor Asp.Net Core - asp.net-core

I am working on blazor using asp.net core 6.0 I am facing issue to open bootstrap popup modal. When I click the modal button it doesn't show any modal popup. Also check for inspect elements there is no sign of modal html. I have added bootstrap css on layout. Reference Url is attached.
Here is the link
Here is my implementation
Page
<BlazorTaskItems.Pages.Modal #ref="modal"></BlazorTaskItems.Pages.Modal>
<button class="btn btn-primary" #onclick="() => modal.Open()">Modal!</button>
#code {
private BlazorTaskItems.Pages.Modal modal { get; set; }
}
Component
<div class="modal #modalClass" tabindex="-1" role="dialog" style="display:#modalDisplay; overflow-y: auto;">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">#Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #onclick="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Body
</div>
<div class="modal-footer">
#Footer
</div>
</div>
</div>
</div>
#if (showBackdrop)
{
<div class="modal-backdrop fade show"></div>
}
#code {
[Parameter]
public RenderFragment? Title { get; set; }
[Parameter]
public RenderFragment? Body { get; set; }
[Parameter]
public RenderFragment? Footer { get; set; }
public Guid Guid = Guid.NewGuid();
private string modalDisplay = "none;";
private string modalClass = "";
private bool showBackdrop = false;
public void Open()
{
modalDisplay = "block;";
modalClass = "show";
showBackdrop = true;
}
public void Close()
{
modalDisplay = "none";
modalClass = "";
showBackdrop = false;
}
}

You need to call StateHasChanged(); (which happens to be in your linked code...)
public void Open()
{
modalDisplay = "block;";
modalClass = "show";
showBackdrop = true;
StateHasChanged();
}
Make sure to do this in the Close() method also.

Related

drop down display empty rows although i get data filled on RefreshDropDownList function?

I work on blazor on .net core 7 . i face issue when display drop down server type
issue is drop down server type display empty although I get data on function RefreshDropDownList(); .
I work on blazor page server names data and inside this page there are drop down servertype
so server type drop down exist on another page ServersNames
server type drop down display empty although function RefreshDropDownList() return 4 items data .
so what is issue and How to solve it ? .
controller action fill drop down is
[HttpGet]
public IActionResult GetAll()
{
return Ok(_IserverTypeService.GetAll());
}
I test action GetAll on controller service type and it return data without any issue
on blazor ui :
<h1>Server Name</h1>
<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal" #onclick="AddClick">
Add ServerNames
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">
#ModalTitle
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</h5>
</div>
<div class="modal-body">
<div class="d-flex flex-row bd-highlight mb-3">
<div class="p-2 w-100 bd-highlight">
<div class="form-group row">
<label for="example-text-input" class="col-3 col-form-label">Server Type</label>
<div class="col-9">
#* <input type="text" class="form-control" #bind="server_Type" />*#
<select class="form-select" #bind="server_Type">
#foreach (var servertype in ServerType)
{
<option value="#servertype.serverTypeId">
#servertype.serverType
</option>
}
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#code
{
public class ServerNamesClass
{
public string server_Type { get; set; }
}
public class ServerTypesClass
{
public int serverTypeId { get; set; }
public string serverType { get; set; }
}
private IEnumerable<ServerTypesClass> ServerType = Array.Empty<ServerTypesClass>();
protected override async Task OnInitializedAsync()
{
await RefreshDropDownList();
}
private async Task RefreshDropDownList()
{
var request = new HttpRequestMessage(HttpMethod.Get, config["API_URL"] + "ServerTypes");
var client = ClientFactory.CreateClient();
var response = await client.SendAsync(request);
using var responsestream = await response.Content.ReadAsStreamAsync();
ServerType = await JsonSerializer.DeserializeAsync<IEnumerable<ServerTypesClass>>(responsestream);
ServerType = Array.Empty<ServerTypesClass>();
}
private async void AddClick()
{
await RefreshDropDownList();
}
In your RefreshDropDownList() you overwrite your ServerType IEnumerable with an empty list: ServerType = Array.Empty<ServerTypesClass>();. This means that your deserialized data will always be overwritten with an empty list.

Show Post submit popup message in ASP.Net Core Razor page without controller

I have an ASP.Net Core Razor web application without controllers.
I have a form in my cshtml page and on Post/Submit I am calling an external API, which returns a success message or an error message. I want to show this message in my page as a popup.
I tried multiple things but failed. Here is my code.
In my "Index.cshtml"
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address"/>
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
In my Index.cshtml.cs
[BindProperty]
public string SubscriptionEmail { get; set; }
public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }
public async void OnPostNewsSubscription()
{
try
{
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = string.Empty;
using (HttpClient _httpClient = _httpClientFactory.CreateClient("PortalBasicHttpClient"))
{
if (!string.IsNullOrEmpty(SubscriptionEmail))
{
HttpRequestMessage _Request = new(HttpMethod.Post, _httpClient.BaseAddress + "Api/SaveSubscriptionEmail/" + SubscriptionEmail);
HttpResponseMessage _Response = await _httpClient.SendAsync(_Request);
if (_Response.IsSuccessStatusCode)
{
this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
}
else
{
this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = ex.Message;
}
}
My code behind is working fine, but not sure how to grace fully show this in the razor page using bootstrap.
looking forward for some guidance.
I tried using modal popup, but the text was not updated in the label I used in the modal popup and the pop-up disappeared with in few seconds, even though there was a "ok" button.
I also tried to use the java script method as mentioned in the following link https://www.aspsnippets.com/Articles/ASPNet-Core-Razor-Pages-Display-JavaScript-Alert-Message-Box.aspx
I will be great help if someone can help with a sample code.
Please debug your code and be sure the two properties actually contain the value you want.
The following working demo I just hard coded the two properties value for easy testing in the backend:
Index.cshtml
#page
#model IndexModel
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
#if (Model.ActionResultMessageText == string.Empty)
{
<script type="text/javascript">
window.onload = function () {
alert("#Model.ActionResultErrorMessageText");
};
</script>
}
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty]
public string SubscriptionEmail { get; set; }
public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }
public void OnGet()
{
}
public async void OnPostNewsSubscription()
{
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = "error";
}
}
Result:
If you want to use Bootstrap modal popup, change your page like below:
#page
#model IndexModel
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#Model.ActionResultErrorMessageText
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#if (Model.ActionResultMessageText == string.Empty)
{
<script type="text/javascript">
window.onload = function () {
$("#exampleModal").modal("show")
};
</script>
}
Result:

My web page is left without any reaction after the website is launched and the page is locked

I have web page and My web page is left without any reaction after the website is launched and the page is locked. Codes are as bellow:
#attribute [Authorize]
#inject IReciption _Reception;
<section class="p-top-10 p-bottom-10 bgcolor rtl">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="shortcode_modules">
<div class="modules__title">
<h3>Reception</h3>
#*<h3>RegReception<InfoBoxComponent StrMessage="#Message1"></InfoBoxComponent></h3>*#
</div>
<div class="text-center module--social">
<div class="social social--color--filled">
<ul>
<li>
<div>
<input type="text" #bind-value="#StrSerialNumber" placeholder="SerialNumber">
</div>
</li>
<li>
#if (!IsSaveLoading)
{
<button class="btn btn-primary" #onclick="(() => CheckTheSerial())" style="margin-top:15px;">Testing</button>
}
else
{
<button class="btn btn-primary" style="margin-top:15px;">
<i class="fa fa-spin fa-spinner"></i> Searching
</button>
}
</li>
#if (prodSrCls.Responses.Statue != LosacoWeb.Shared.Enumes.StatueResponse.NoStatus)
{
#if (prodSrCls.Responses.Statue == LosacoWeb.Shared.Enumes.StatueResponse.Success)
{
<br />
<li><h4><b class="primary">Group:</b> #prodSrCls.GoodsGroupItem_Name</h4></li>
<br />
<li><h4><b class="primary">Model:</b> #prodSrCls.Goods_GoodsName </h4></li>
}
#if (prodSrCls.Responses.Statue == LosacoWeb.Shared.Enumes.StatueResponse.Failed)
{
<br />
<li>
<h3>
<span class="danger icon-close"></span><b class="danger">
Serial Is not Correct
</b>
</h3>
</li>
}
}
</ul>
</div>
</div>
</div>
</div>
<!-- end .col-md-6 -->
</div>
<!-- end .row -->
</div>
<!-- end .container -->
</section>
And C# Programming Code Part Is As Bellow:
public bool IsSaveLoading = false;
private string serial;
public String StrSerialNumber
{
get
{
return serial;
}
set
{
serial = value;
TextChangedEvetFotCleaning();
}
}
ProdSerialClasses prodSrCls
= new ProdSerialClasses();
[Parameter]
public EventCallback<ProdSerialClasses> OnFindSerial { get; set; }
protected override async Task OnInitializedAsync()
{
IsSaveLoading = false;
}
My answer is that how I can resolve my problem. I have to use this code in a online shop project. My other pages work fine. but this page become lock after run.
Hi. Change second part to :
public bool IsSaveLoading = false;
public String StrSerialNumber = "0";
ProdSerialClasses prodSrCls = new ProdSerialClasses();
[Parameter]
public EventCallback<ProdSerialClasses> OnFindSerial { get; set; }
protected override async Task OnInitializedAsync()
{
IsSaveLoading = false;
}
you must add value to you variable StrSerialNumber = "0" because in can cause of error with null value.
I hope your code problem is solved this way.
You should also check for prolapse before using prodSrCls. If it is not null, you can use it. If you do not bet, you may still get the error.
#if(prodSrCls != null)
{
// your codes . . .
}
Please do not forget to confirm the answer.

How do I make a simple asp.net Core 6 page that sends the form data back to itself for modification with the answer?

I am wanting to replace windows forms small projects with ASP.net core 6. To do that I need to be able to send the form data back to the same form page so that it can be updated on the fly. So the form still holds the data when the page reloads, and holds the answer in a section below it.
I don't need the usual Database, and CRUD structure.
That way the user can refine it for what they want.
I think its something to do with [bindproperty].
Here is my working so far....
Main form
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<form>
<div class="mb-3">
<div class="row g-3">
<div class="col">
<label>Enter the Room Width</label>
<input asp-for="#Model.carpet.RoomWidth" type="number" class="form-control w-25" >
</div>
<div class="col">
<label>Enter the Room Length</label>
<input asp-for="#Model.carpet.RoomLength" type="number" class="form-control w-25" >
</div>
<div class="col">
<label>Enter the Carpet Type</label>
<select asp-for="#Model.carpet.CarpetType" asp-items="#Model.carpetTypesList"></select>
</div>
</div>
<div class="form-check">
<input class="form-check-input" asp-for="#Model.carpet.InstallationCost">
<label class="form-check-label" >Do you want us to install the Carpet?</label>
</div>
<div class="form-check">
<input class="form-check-input" asp-for="#Model.carpet.UnderlayCost">
<label class="form-check-label" >Do you want Underlay for your Carpet?</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit Your Carpet Details</button>
</form>
This is the back end. The calculations are all in CarpetOperations, and Carpet is the model.
public class IndexModel : PageModel
{
[BindProperty]
public Carpet carpet { get; set; }
public List<SelectListItem> carpetTypesList { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Cheap" },
new SelectListItem { Value = "2", Text = "Home" },
new SelectListItem { Value = "3", Text = "Luxurious" },
};
public CarpetOperations carpetOperations { get; set; }
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
Thanks for your help.
Solved it!
For anyone who ever sees this in the future
[BindProperty(SupportsGet = true)]
public Carpet? carpet { get; set; }
and do whatever you need in the OnPostAsync
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
carpet.InstallationCost = 20;
carpet.UnderlayCost = 20;
carpet.RoomArea = Convert.ToSingle(carpet.RoomWidth) * Convert.ToSingle(carpet.RoomLength);
carpet.FinalCost = carpetOperations.TotalInstallCost(carpet);
}
return Page();
}

asp.net Core 2 Razor Pages problem loading partial inside conditional

I created a partial page view that is a box that for displaying form validation errors:
<div class="alert alert-danger" role="alert">
<div class="row">
<div class="col-auto align-self-center">
<i class="fas fa-times-circle fa-2x"></i>
</div>
<div asp-validation-summary="All"></div>
</div>
From the main page view, I want to load this partial page view only if any validation errors exist:
#if (ViewData.ModelState.ErrorCount > 0)
{
<partial name="Partial/_ValidationErrorSummary"/>
}
When I first load the page the error summary does not display, which is what I want. But when I try to submit the form on the page nothing happens. If I remove the conditional #if (ViewData.ModelState.ErrorCount > 0) from the main page view, I am able to submit the form as expected. What am I doing wrong?
Full Page HTML
#page
#model RegisterModel
#{
ViewData["Title"] = "Sign Up";
}
<div class="row">
<div class="col-md-6 offset-md-3">
<form asp-route-returnUrl="#Model.ReturnUrl" method="post">
#if (ViewData.ModelState.ErrorCount > 0)
{
<partial name="Partial/_ValidationErrorSummary" />
}
<div class="form-group">
<label asp-for="Input.Email">Email</label>
<input asp-for="Input.Email" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Input.Password">Password</label>
<input asp-for="Input.Password" type="password"class="form-control" />
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword">Confirm Password</label>
<input asp-for="Input.ConfirmPassword" type="password" class="form-control" />
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Submit</button>
</form>
</div>
</div>
Still not reproduce , but provide a code sample which meets your requirement , you can check that with your codes :
Create a Razor page template asp.net core application .
Create Partial folder inside Pages folder and add _ValidationErrorSummary.cshtml, use your codes .
Create a Razor page and use view model :
public class RegisterModel : PageModel
{
[BindProperty]
public Input Input { get; set; }
public string ReturnUrl { get; set; }
public void OnGet()
{
ReturnUrl = "Create";
}
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
// do something
return RedirectToPage("Contact");
}
else
{
return Page();
}
}
}
public class Input
{
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string ConfirmPassword { get; set; }
}
Put your html in page's html .
The above codes works as expected , if any other concern please feel free to let me know .