Show Post submit popup message in ASP.Net Core Razor page without controller - asp.net-core

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:

Related

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

Bootstrap Modal Popup using Blazor 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.

Asp.net Core Upload File Does not Fire OnPost Code

First thing first i want to apology if this topic has been mentioned before, but i looked for 2 days and never find about my problem.
So, I have a IFormFile script, which is does not throw any error (at least a syntax error) but when i am in the Upload Page, i complete my fields (Name,Description and File) and press Upload button, my OnPost code does not Fire at all and my page just referesh.
This is my Razor Page CREATE.CSHTML
#page
#model Appuntamenti.Models.ViewModel.DocumentCreateViewModel
#{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<div>
<h4>Upload Single file</h4>
</div>
<form method="post" enctype="multipart/form-data" runat="server" asp-action="OnPost" class="mt-3">
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="Name..." />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Description" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Description" class="form-control" placeholder="Description..." />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Document" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="Document" class="form-control custom-file-input" />
<label class="custom-file-label">Choose File..</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success form-control"></button>
#section Scripts {
<script>
$(document).ready(function ()
{
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
</form>
And This is my CREATE.CSHTML.CS page
namespace Appuntamenti.Pages.Documents
{
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _db;
private readonly IHostingEnvironment _hostingEnvironment;
public CreateModel(ApplicationDbContext db, IHostingEnvironment hostingEnvironment)
{
_db = db;
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task<IActionResult> OnPostAsync (DocumentCreateViewModel model)
{
if (!ModelState.IsValid)
{
return NotFound();
}
string uniqueFileName = null;
if(model.Document != null)
{
string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "Documents");
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Document.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
await model.Document.CopyToAsync(new FileStream(filePath, FileMode.Create));
}
DocumentModel newDocument = new DocumentModel
{
Id = model.Id,
Name = model.Name,
Description = model.Description,
DocumentPath = uniqueFileName
};
_db.Add(newDocument);
_db.SaveChanges();
return RedirectToPage("./Index");
}
}
}
And Those are my 2 Models for the IFormFile
public class DocumentModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string DocumentPath { get; set; }
}
public class DocumentCreateViewModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public IFormFile Document { get; set; }
}
BAsically i tried to put a Breakpoint on the Post Method but it does not fire at all,
I tried to run the Website and inspect the elements,header and network and everything is ok.
After some browsing i read that the Onpost method with the IFormFile rely on the TokenValidation, i tried to ignore the validation and see if something change but nothing. I really dont know what i am doing wrong.
I hope i made my point and problem clear and please if you need more info just let me know
You mixed up Asp.Net Core MVC and Razor Page.
Follow steps below:
CreateModel
public class CreateModel : PageModel
{
[BindProperty]
public DocumentCreateViewModel DocumentCreateViewModel { get; set; }
//[HttpPost]
public async Task<IActionResult> OnPostAsync()
{
return RedirectToPage("./Index");
}
View
#page
#model CreateModel
#{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<div>
<h4>Upload Single file</h4>
</div>
<form method="post" enctype="multipart/form-data">
<div class="form-group row">
<label asp-for="DocumentCreateViewModel.Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="DocumentCreateViewModel.Name" class="form-control" placeholder="Name..." />
<span asp-validation-for="DocumentCreateViewModel.Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="DocumentCreateViewModel.Description" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="DocumentCreateViewModel.Description" class="form-control" placeholder="Description..." />
<span asp-validation-for="DocumentCreateViewModel.Description" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="DocumentCreateViewModel.Document" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="DocumentCreateViewModel.Document" type="file" class="form-control custom-file-input" />
<label class="custom-file-label">Choose File..</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success form-control"></button>
#*<input type="submit" value="Submit" />*#
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(document).ready(function () {
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
For more information about Razor page, refer Introduction to Razor Pages in ASP.NET Core

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 .