ASP.NET Core 6 MVC : PagedListPager ValidateAntiForgeryToken - asp.net-core-mvc

I am writing an ASP.NET Core 6 MVC app, and I am using X.PagedList to do paging.
In my table I set this for Paging
#Html.PagedListPager((IPagedList)Model.SearchResultViewPaging, page =>
Url.Action("ResultPaging", "Participant", new { page = page }))
The method in the controller is decorated with a [ValidateAntiForgeryToken] annotation. I have this as a warning of Veracode.
In Javascript, this is the call I use to send
headers: {
"RequestVerificationToken":
$('input:hidden[name="__RequestVerificationToken"]').val()
},
How can I send this as a header?
Thanks

Related

Is it possible to refresh a View Component in an ASP.NET Core 2.1 Razor page?

Is it possible to refresh a View Component in an ASP.NET Core 2.1 Razor page?
I discovered that this is possible in ASP.NET MVC using AJAX—see solutions at Viewcomponent alternative for ajax refresh and ViewComponents are not async. But what about ASP.NET Core?
One solution I found is basically to have a controller returning the View Component, and then using AJAX to do the refresh.
This is example is borrowed from ViewComponents are not async
~/HelloWorldViewComponent.cs
public class HelloWorldViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
var model = new string[]
{
"Hello", "from", "the", "view", "component."
};
return View("Default", model);
}
}
~/HomeController.cs (I cannot get this part working in razor pages)
public class HomeController : Controller
{
public IActionResult GetHelloWorld()
{
return ViewComponent("HelloWorld");
}
}
~/Views/Shared/Components/HelloWorld/Default.cshtml
#model string[]
<ul>
#foreach(var item in Model)
{
<li>#item</li>
}
</ul>
~/wwwroot/index.html
<body>
<script src="js/jquery.min.js"></script>
<script>
$.get("home/GetHelloWorld", function(data) {
$("body").html(data);
});
</script>
</body>
My problem is that I cannot get a controller working together with Razor Pages, I cannot figure out if that's even possible.
TLDR
Open Startup.cs and replace this
app.UseMvc();
with this
app.UseMvcWithDefaultRoute();
Details
The ASP.NET Core Razor Pages template (dotnet new razor) does not come with controller routes because it does not come with controllers. The easiest way to add controller routes is via UseMvcWithDefaultRoute(), which is the equivalent of the following:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
With that route installed, the URL ~/Home/GetHelloWorld maps to the HomeController.GetHelloWorld() action.
Here is a GitHub commit that demonstrates your use case in a new ASP.NET Core Razor Pages app.
See Also
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1
To do this within the RazorPage ensure that the handler method follows the convention OGet[MyMethodName] and this should resolve your routing issue
public class HomeController : Controller
{
public IActionResult OnGetHelloWorld()
{
return ViewComponent("HelloWorld");
}
}
And modify the get request to make use of the handler
<body>
<script src="js/jquery.min.js"></script>
<script>
$.get(window.location.href.split('?')[0] + "?handler=HelloWorld", function(data) {
$("body").html(data);
});
</script>
</body>
Various example are available at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio

Best Practice for showing Page after Post

I have a View with a Form that calls a controller action Post Method to "Complete" a Package. It then needs to refresh the page its on as that contains information that will be updated, both within the view itself and also within a partial. It does use two different Controllers in different MVC Areas.
The Post works correctly and the redirect is issued, but the page is not refreshed.
I have read that instead, I should use OnSuccess within the Ajax call that calls Complete, but I thought that was for in page calls, not ones that navigate to different pages.
View Form
#using (Ajax.BeginForm("Complete", "Packages", new { Area = "Core" },
new AjaxOptions
{
HttpMethod = "POST"
}))
{
Core(Area) Packages Controller
[HttpPost]
public ActionResult Complete(int ID)
{
// Update code
// Refresh the full page
return RedirectToAction("Summary", new { Area = "Control", id = packageBuilder.CurrentPackage.ID });
}
Control (Area) Packages Controller
[HttpGet]
public ActionResult Summary(int id)
{
// Get Model
return View("Summary", model);
}
Any pointers would be warmly welcomed.
Thanks,
Chris.
The reason that your page is not refreshed after you submit the form and the redirect is not issued in the browser, is that you are submitting the request over AJAX. This is a request issued by the browser behind the scenes.
If you want to submit the form and for the page to be refreshed, I'd recommend changing your code from Ajax.BeginForm(... to Html.BeginForm(... and then it will load the page and perform the redirect as expected.
I am not quite sure how your ajax calls are structured, but if you are using the MVC Ajax helper you can just call `location.reload(); in the OnComplete method, like so:
#using (Ajax.BeginForm(new AjaxOptions{OnComplete = "javascriptfunction"}))
{
//Data and submit button
}
<script>
function javascriptfunction(){
location.reload();
}
</script>

How to show the view of method in controller when data passed from ajax in ASP.NET MVC

I am developing MVC application.
I want pass the values from View to controller.
I have use ajax to pass the values from View to controller.
Now this data goes perfectly into method....
$(document).ready(function () {
$('#CheckOrder').click(function(){
PassData();
});
function PassData()
{
$.ajax({
url: '#Url.Action("ShowWHOrder", "Order")',
type: 'POST',
data: { OrderNo: #ViewBag.OrderNo, OrderTo : '#ViewBag.OrderTo' }
});
}
});
Here is the method... in below method all parameters comes properly.
[HttpPost]
public ActionResult ShowWHOrder(string OrderNo, string OrderTo)
{
ViewBag.OrderNo = OrderNo;
ViewBag.OrderTo = OrderTo;
return View();
}
Now, I have added the new view for this method.
But It doesn't redirect to new view, it remains on previous view only.
Is due to ajax ?
What option I have to show the new view ?
How can I implement this without ajax ?

razor: ignore httprequestvalidationexception

I am using MVC3 Razor. I want my server to ignore the httprequestvalidation exception. I have tried
and all codes like [ValidateInput(false)]
none of these codes seem to work with MVC3 .net framework 4.0 razor
[ValidateInput(false)]
public ActionResult Index()
{
// ...method body
}
Using MVC 3, you must also ensure this is in your Web.config:
<system.web><httpRuntime requestValidationMode="2.0" /></system.web>

Ajax.BeginForm OnFailure invoked with Response, not AjaxContext

When writing Ajax data entry forms in my ASP.NET MVC3 app, I have a standard Ajax error handler, along the lines of:
function handleAjaxError(ajaxContext) {
var response = ajaxContext.get_response();
var statusCode = response.get_statusCode();
alert("Request failed, status code " + statusCode);
}
I'm now finding that the parameter sent to handleAjaxError isn't an Ajax context but the Response object itself, for some reason.
Is this a known behavior change in MVC3, maybe? Here's the form setup, if that's relevant:
#using (Ajax.BeginForm("Create", "Attendance", null, new AjaxOptions
{ OnFailure = "handleAjaxError",
OnSuccess = "alert('success')" },
new { id = "frmCreateException" }))
{
#Html.EditorFor(m => Model)
}
The controller action returns a PartialViewResult. The HTTP Exception at the moment is a 500, because I haven't yet created the view.
Thanks!
Is this a known behavior change in MVC3, maybe?
Yes, ASP.NET MVC 3 uses unobtrusive jQuery for AJAX stuff contrary to previous version which used Microsoft*.js. So the first argument passed to the error handler is the jqXHR object.
And to get the response text and status code:
alert(ajaxContext.status);
alert(ajaxContext.responseText);

Resources