onget handler razor pages - asp.net-core

I have a button on a GET Form on asp.net core razor pages
<form method="get" asp-page="Index">
<button type="submit" asp-page="Index" asp-page-handler="Something" class="btn btn-primary"></button>
</form>
and the code behind
public IActionResult OnGetSomething(){
//... some code
return Page();
}
My problem is the onget handler code is never executed
If the form is POST the onpost handler will work fine but if it is GET it doesn’t work
So what am I missing here? and how to make the onget handler work?

When you submit a form using GET, the browser trashes query string values in the form action and replaces them with a new query string built from the form fields. You can hit your handler by adding an appropriate hidden field to the form:
<form method="get" asp-page="Index">
<input type="hidden" name="handler" value="Something" />
<button type="submit" class="btn btn-primary">Get</button>
</form>

you can't go to get method because of parameters miss matching.
Suppose:
In controller
[HttpGet]
public IActionResult Create()
{
return View();
}
//Post Method
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(string Name)
{
}
In View:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>]
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
Then it go post method cause it has 1 parameters (Name). if we not net any input or parameters are not same then it hit different method.
It the concept of method overloading
In details of method overloading https://www.geeksforgeeks.org/c-sharp-method-overloading/

Related

Why did i get Status Code: 405; Method Not Allowed after trying to execute the delete action?

ASP.NET Core 5.0, EF Core 5.0
My action :
[HttpPost("id")]
public IActionResult DeleteEquipment(int id)
{
repository.DeleteEquipment(id);
return View("WorkoutDB");
}
My ef method:
public void DeleteEquipment(int Id)
{
_context.Remove(new Equipment() { EquipmentId = Id });
_context.SaveChanges();
}
My button from partial view:
<input type="button" value="Delete" class="btn btn-danger" onclick="location.href='#Url.Action("DeleteEquipment", "Admin", item.EquipmentId)'" /
I don't know is it normal code or not, i am newbie, but i spent 4 hours and couldn't get the result.
Thanks for you attention!
UPD:
I changed my button
<td>
<form asp-action="DeleteEquipment" method="post">
<input type="hidden" name="EquipmentId" value="#item.EquipmentId" />
<button type="submit" class="btn btn-danger btn-sm">
Delete
</button>
</form>
</td>
But its still not working. I cant bind correct value to EquipmentId. Always 0 value. Why?
location.href='#Url.Action("DeleteEquipment", "Admin", item.EquipmentId)' cause browser to redirect user to new url. Redirect cause GET Request but your DeleteEquipment method has HttpPost attribute.
Replace
[HttpPost("id")]
with
[HttpGet("{id}")]
As #mason mentioned if you need to call your api with POST Request you need to use form.
<form asp-action="DeleteEquipment" asp-controller="Admin" asp-route-id="#item.EquipmentId">
<input type="submit" class="btn btn-danger" value="Delete" />
</form>

How to create object and send it to OnPost in Razor Pages?

How to create object and send it to OnPost in Razor Pages?
<form method="post">
<div>
<label>Add Text</label>
<input asp-for=SentimentData.SentimentText class="form-control" />
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
public void OnPost(SentimentData SentimentData)
{
Text = SentimentData.SentimentText;
Analysis.Evaluate(mlContext, Model, SplitDataView.TestSet);
Analysis.UseModelWithSingleItem(mlContext, SentimentData, Model, Text);
}
But after my input field SentimentText is null. i dont know why.

NET Core - Submit on input change, not button click

Currently, I have a form that calls a method in my controller. It sends a string as a parameter to my IActionResult (the string is always a numer since I am getting it from an input of type range between 1 and 12). The method looks like this: public IActionResult ChangeForecastMonths(string forecastMonths) The code in my view is the following:
<form asp-action="ChangeForecastMonths">
<input asp-for="FutureForecastMonths" name="forecastMonths" type="range" class="custom-range" min="1" max="12" step="1" />
<input type="submit" value="Save" class="btn btn-primary" />
</form>
What I'm trying to do is -- instead of the ChangeForecastMonths method being called whenever the submit button is clicked -- to actually have it called whenever the input field changes its value.
You could hook to the change() event of the input, then fire a submit() on the parent form, like this:
<form asp-action="ChangeForecastMonths">
<input asp-for="FutureForecastMonths" name="forecastMonths" type="range" class="custom-range" min="1" max="12" step="1" />
<input type="submit" value="Save" class="btn btn-primary" />
</form>
#section Scripts
{
<script>
$('form input').change(function() {
$(this).closest('form').submit();
});
</script>
}
Result:

Razor Pages - Run a server side method NOT using post

In Razor pages ASP.NET Core, how do I do a basic onclick event for a button which is of type button?
Do I need to wire up an AJAX GET request to get the below "Resend Code" button to work? There is plenty of chatter about OnPost this and that.. but I don't want to post.
Can't be this hard?
<form method="post">
<div asp-validation-summary="All"></div>
<div class="form-group-item">
<label asp-for="Input.TwoFactorCode"></label>
<input asp-for="Input.TwoFactorCode" class="input" />
<span asp-validation-for="Input.TwoFactorCode"></span>
</div>
<div class="form-group-item">
<label class="margin-0" asp-for="Input.RememberMachine">
<input asp-for="Input.RememberMachine" />
#Html.DisplayNameFor(m => m.Input.RememberMachine)
</label>
</div>
<div>
<button type="button" asp-page-handler="ResendCode" class="btn btn-light">Resend Code</button>
<button type="submit" class="btn btn-secondary">Confirm</button>
</div>
</form>
As it stands, the button won't do anything. You can use JavaScript to intercept the button click and then fire a get request using AJAX (jQuery example below):
$('.btn.btn-light').on('click', function(){
$.get('?handler=ResendCode', data, function(){
...
});
});
You can try changing the button to use formmethod="get":
<button type="submit" formmethod="get" asp-page-handler="ResendCode" class="btn btn-light">Resend Code</button>
Note, this will only work for buttons that have type="submit" or type="image" (other type-values don't cause the form to submit). Also it's an HTML5 attribute.
Reference:
https://html.com/attributes/input-formmethod/
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formmethod
maybe try making your own custom handler methods other than OnPost() and OnGet()

How to prevent immediate trigger jQuery validation?

There is some ViewModel:
class MyViewModel
{
[Required(ErrorMessage = "Field {0} is required")]
public string Email { get; set; }
}
I use jquery validation for front-end:
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js">
</script>
The fragment of Razor markup:
<form asp-controller="Account" asp-action="Register" role="form">
<div class="form-group">
<div asp-validation-summary="All" class="text-danger"></div>
</div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" aria-describedby="email" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</form>
The issue is validation is triggered immediately when user get the html page. So one sees error for email field when she inputs nothing yet (Field Email is required). How can I prevent this behavior (triggered on submit)?
There is action:
public IActionResult SomeAction(MyViewModel model = null)
{
return View(model);
}
i.e. controller pass to action null model (value by default). It is the reason of that behavior of jquery validation