(Using ASP.NET Core 3.1 - Razor Pages web application)
I am trying to trigger OnPost method which is in Areas >> Login >> Pages >> Index.cshtml.cs Razor Page. Somehow, it triggers OnGet method but when I try to post a form, it didn't trigger OnPost method.
Index.cshtml.cs
namespace WebApplication1.Areas.Login.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
//triggering
}
public void OnPost()
{
//not triggering
}
}
}
Index.cshtml
#page
#model WebApplication1.Areas.Login.Pages.IndexModel
#{
}
<form method="post">
<input name="UserId" class="form-control" />
<input type="submit" value="Create" class="btn btn-primary" />
</form>
Note:
If I am not using Areas, OnGet and OnPost working fine.
I have tried below but none of them worked for me:
Tried https://www.learnrazorpages.com/advanced/areas
How can Add Area in razor pages on dot net core 3.0/3.1?
I found the answer here: I have added the following code in Areas → Login → Pages
_ViewImports.cshtml:
#using WebApplication1
#namespace WebApplication1.Web.Areas.Login.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Related
Using the NET 6 core application with Pages.
Right out of the box the project has the following "code behind"
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
// This is this the new code
public void MyCustomMethod()
{
var debug = "Stop Here debug break point";
}
}
The front end has the following:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<form action="MyCustomMethod" method="get">
<input type="submit" />
</form>
</div>
Unable to GET or POST to the custom method (MyCustomMethod) in the NET 6 CORE using PAGES.
It could be a dumb question by I tried to google for the past 2 hours and can not find anything related to what I am doing. Please help.
Trying to use a simple form to get or post to the "code behind". When page load I do see a debug going into OnGet() method which it should do but clicking on a button in a form it never makes it into MyCustomMethod().
Thank you.
Did the following change to a code:
[HttpPost] // Second run added this because it was still not working
public void OnPostMyCustomMethod()
{
var debug = "Stop Here debug break point";
}
Front page
<form action="MyCustomMethod" method="post">
<input type="submit" />
</form>
Still unable access:
Debug Run
Razor Pages includes a feature called "named handler methods". This feature enables you to specify multiple methods that can be executed for a single verb.
If you have set the OnPostMyCustomMethod or MyCustomMethod in the backend codes, you should use this url "https://localhost:7086/?handler=MyCustomMethod" to access it.
More details, you could refer to below example:
<form asp-page-handler="MyCustomMethod" method="post">
<input type="submit" />
</form>
I need to remove an item in Cart with razor page. For this i used a form with asp-page-handler.
Cart.cshtml :
<td class="text-center">
<form asp-page-handler="Remove" method="post">
<input type="hidden" name="id" value="#line.Product.Id" />
<input type="hidden" name="returnUrl" value="#Model.ReturnUrl" />
<button type="submit" class="btn btn-sm btn-danger">
Remove
</button>
</form>
</td>
And my Cart.html.cs has a OnPostRemove method like this:
public IActionResult OnPostRemove(int id, string returnUrl)
{
Cart.RemoveLine(Cart.Lines.First(cl =>
cl.Product.Id == id).Product);
return RedirectToPage(new { returnUrl = returnUrl });
}
When i cliked remove button i got a 400 Error and my OnPostRemove method doesn't trigger.
Update
I included tag helper in my _ViewImports.cshtml and issue resolved.
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Put the page handler inside the submit button tags.
<form method="post">
...
<button type="submit" asp-page-handler="Remove">
Remove
</button>
</form>
The code snippet that you shared seems ok, which work well with testing data on my side.
When i cliked remove button i got a 400 Error and my OnPostRemove method doesn't trigger.
To troubleshoot the issue, please check the actual request with the posted data in F12 developer tool Network tab.
And please note that if the antiforgery token validation is enabled, but the request does not include a valid antiforgery token or something wrong with the antiforgery cookies, which would also cause 400 Bad Request error.
For testing purpose, you can try to skip antiforgery token validation by applying IgnoreAntiforgeryTokenAttribute on page model class, then check if the request can be handled as expected.
[IgnoreAntiforgeryToken]
public class CartModel : PageModel
{
I am using Visual Studio 2019 Community16.3.0 Preview 4.0, .NET Core 3.0 RC1, ASP.NET Core 3, Entity Framework 3 RC1
I am reading ASP.NET Core document. I know ASP.NET Core has 4 programming models:
Razor page
ASP.NET MVC
ASP.NET Web API
ASP.NET Blazor
First question: I wonder, Can I have 2 different ASP.NET Core programming models in same web-app?
Second question: I create an Blazor web app follow this tutorial: https://docs.devexpress.com/Blazor/401057/getting-started/create-a-new-application , it run success.
Blazor
#page "/weather"
<h1>Weather</h1>
<DxTextBox></DxTextBox>
#code {
//...
}
I try to put ASP.NET Core Razor page programming model to existing Blazor web-app
Create.cshmtml
#page "/Create"
#model RazorPagesMovie.Pages.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Movie</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Movie.Title" class="control-label"></label>
<input asp-for="Movie.Title" class="form-control" />
<span asp-validation-for="Movie.Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Movie.ReleaseDate" class="control-label"></label>
<input asp-for="Movie.ReleaseDate" class="form-control" />
<span asp-validation-for="Movie.ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Movie.Genre" class="control-label"></label>
<input asp-for="Movie.Genre" class="form-control" />
<span asp-validation-for="Movie.Genre" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Movie.Price" class="control-label"></label>
<input asp-for="Movie.Price" class="form-control" />
<span asp-validation-for="Movie.Price" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Create.cshmt.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using acc133blazor.Models;
namespace RazorPagesMovie.Pages
{
public class CreateModel : PageModel
{
private readonly foo.Models.fooContext _context;
public CreateModel(foo.Models.fooContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public Movie Movie { get; set; }
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Movie.Add(Movie);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
I am not sure it can run success. I try debug web-app, go to Razor page https://localhost:44303/Create and error.
But its Blazor componets set is still not sufficiency (in beta, just 12 components https://demos.devexpress.com/blazor/ ), I try to add ASP.NET Razor page, or ASP.NET Core Control (ASP.NET Core ViewComponent https://demos.devexpress.com/ASPNetCore/), Can I do this?
There's no problem without using Blazor to combine together.
For Blazor, although you could combine it with Razor Pages but the asp-page ,asp-for tag helper will not work any more.
Refer to Blazor Component Embedded in Razor Page
Link to a page with a Blazor component and all of the other page links will no longer function. You can even replicate the same situation using the boilerplate template app for a Blazor Server Side app and linking to any mvc view or razor page. All links no longer work. This has to be a Startup issue. Removing
endpoints.MapBlazorHub(); will allow the links to work again but obviously that breaks the Blazor component.
For partial view/view components, they are aslo not working in Blazor, they could be changed to a razor component.
Refer to Can you use a ViewComponent in a Blazor layout
https://github.com/aspnet/Blazor/issues/1066
I'm using ASP.NET Core 2.2.
I'm trying to pass an ID (Guid) from my view to my controller Index using a submit button decorated with asp tag helpers like below:
<input type="submit" value="Go" asp-controller="MyController" asp-action="Index" asp-route-id="#Model.Id" />
My controller action method looks like this:
public IActionResult Index(Guid id)
{
return View();
}
The id is always coming through as Guid.Empty when the submit button is clicked.
I've switched over to using an anchor tag with the same tag helper values and the id comes through populated correctly:
<a asp-controller="MyController" asp-action="Index" asp-route-id="#Model.Id">Go</a>
I can get around this by styling an anchor to look like a button, but for the sake of understanding, can someone explain why an anchor would work in this situation but a submit button will not?
UPDATED (with generated HTML)
HTML with submit
<form>
<div class="d-flex">
<input type="submit" value="Go" formaction="" />
</div>
</form>
HTML with anchor
<form>
<div class="d-flex">
Go
</div>
</form>
put the asp-route-id="..." in the form tag, not in the button.
I've started with asp mvc 3, with c# and razor, then. I want to use forms with security for send petitions POST.
I want to with razor render some like that
<form action="/sass/" method="post">
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-group">
<label>Ingresa tu Nombre</label>
<input class="form-control" name="nombre" />
</div>
<div class="form-group">
<input type="submit" value="Enviar mi duda" class="btn btn-primary btn-sm" />
</div>
}
And in C# I dont know how to validate that csrf token, is valid.
I work with C#, asp mvc3 and razor.
Please help me!
In your action method you need to add the respective attribute [ValidateAntiForgeryToken], and it validate the input for you.
You have a problem with the state of your code. There are two embedded forms: the outer one and the one produced by Html.BeginForm. However, the way to validate the token is to decorate the target action or controller with [ValidateAntiForgeryToken].
So either:
[ValidateAntiForgeryToken]
public ActionResult Index()
{
return View();
}
or to validate all methods in the controller:
[ValidateAntiForgeryToken]
public class MyController : Controller
{
}