I have two types of functionality for a action with a bool
variable.
[HttpGet]
public ActionResult action(bool data = false)
{
if(data == false)
{
return View("view1");
}
else
{
return View("view2");
}
}
It is a [httpGet]
method. some link has data bool value as true
and some has false
.
The url has the attribute like http://localhost:58241/action?data=False
I want to hide the ?data=False
or ?data=True
from URL and should possess all the same functionality like before.
I want the URL like http://localhost:58241/action
Thanks in advance.
You can achieve this functionality partially by making the parameter optional as suggested by @VishalSuthar. But for one condition you must use the parameter if you want to access it using a GET request.
Else, if you make the
Action
only accessible by POST requests, this part will be easier to implement. In that case only change you need is :This way you can pass the parameter in form and hit the action with the URL showing: http://localhost:58241/action
Note: This way the action will not be accessible via GET requests.
bool data = false
this will assign the value when it is missing. So when you call the Url withoutdata
as a parameter then it will assing the value as 'false'As per you requirement, you need to do this:
So everytime,
return View("view1");
will be called no matter what you have passed.Routing has absolutely nothing at all to do with query string parameters. And in any case, you still need to transfer the
data
parameter to the server for the action method to receive it. There are 3 ways to do this:The simplest option is #1, however since you mentioned this isn't acceptable to pass the data through the URL, your only choice is to use HTTP post. So, the rest of this answer uses #2.
First, the default route does not cover your choice of URL (
/action
), so you need to insert a custom route for this.Next, you need a controller to handle both the GET and POST from the browser.
The data is sent back to the server in the POST, so it is not required to pass it in the URL.
Finally, you have the view (named
Action.cshtml
) that is returned from theAction
action method. It has 2 different form tags that submit a different value fordata
depending on the button clicked.Note that you could do this step entirely in JavaScript (AJAX POST) if you please, which would enable you to use a hyperlink instead of a button or you could just style the button using CSS to look like a hyperlink.