I have a listing page (Index) displaying a list of items in a grid. The page consists of a small form at the top and a grid (list) at the bottom. The form serves as a way to filter the items shown in the list.
I need to check if the page is being displayed as a result of submitting the form (clicking any of the 2 buttons) or by clicking a link from another page or by entering the URL directly in the browser's address bar.
The View:
@model MyNameSpace.ViewModels.FooFilterViewModel
@{
ViewBag.Title = "Foo Listing";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
@Html.ValidationSummary(true)
<!-- Field controls used for filtering go here -->
<input id="ClearFilter" type="button" value="Clear Filter" />
<input id="ApplyFilter" type="submit" value="Apply Filter" />
}
<!-- Grid displaying the list of foos goes here -->
The Controller Action:
public ActionResult Index(FooFilterViewModel fooFilterViewModel)
{
// Retrieve all records
IQueryable<Foo> foos = _DBContext.Foos;
if (ModelState.IsValid)
{
if (/* check if coming from form submission */){
// Do something
}
else
{
// Do something else
}
// Code to filter records go here
foos = foss.Where(f => f...........)
}
fooFilterViewModel.Foos = foos;
return View(fooFilterViewModel);
}
Since you're sending your form as GET, as well, all of these methods (submitting the form, following a link, typing the URL in the address bar) are functionally equivalent from the server's point of view. They're all just GET requests for the same URL.
If you just need to differentiate the form submit, you can either add a hidden field or simply name your submit button. Either way, you can then inspect the Request object for this name, and if it exists, you can assume the form was submitted.
<button type="submit" name="FormSubmitted">Submit</button>
Then:
if (Request["FormSubmitted"] != null)
{
// form was submitted
}
However, this can be easily faked. For example, someone could simply type in the URL, http://foo.com/?FormSubmitted, and there'd be no way for you to know. I'm not sure how much a concern malicious users may be in this scenario, but you could somewhat mitigate that by making what you look for more obscure, so it's not as obvious as "FormSubmitted". Or, you could use JavaScript to set something in the form, and then bury that in a minified external file perhaps. Still, security through obscurity is still not security.
Short of that, though, there's no way to tell. Again, all of these methods look exactly the same to a server. In order to differentiate the method, the actual request needs to be different in some way, such as altering the query string, send as POST rather than GET, etc. Otherwise, if it's exactly the same request, the server doesn't know or care how it came about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With