Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current Action name inside the View

In my _Layout page, I have got a search form and each controller has an index view. When the user clicks the search button, it searches in the current index view.

I want to show the search field if the user is index view if they go to other views, I wanted to hide it.

In my _Layout

 <form asp-action="Index" method="get" class="navbar-form form-inline navbar-right">
        <input class="form-control mr-sm-2" id="search" name="search" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success my-2 my-sm-0"  id="BtnSearch" name="BtnSarch" type="submit">Search</button>
    </form>

I am using JQuery at the moment but it is quite difficult to put every single view

    $("#search").hide();
    $("#BtnSearch").hide();

Basically, in my _Layout page, I wanted to show or hide Search form if the user is in the index view. how can i get current view name in _Layout view, please?

like image 707
AliAzra Avatar asked Mar 16 '19 23:03

AliAzra


People also ask

What is action name and controller name in MVC?

Actions are public methods in an MVC controller, that respond to a URL request. Action Selectors are attributes that can be applied to action methods and are used to influence or control which action method gets invoked in response to a request.

How is action method linked to the view?

The following illustrates the Index() action method in the StudentController class. As you can see in the above figure, the Index() method is public, and it returns the ActionResult using the View() method. The View() method is defined in the Controller base class, which returns the appropriate ActionResult .


Video Answer


1 Answers

Basically, in my _Layout page, I wanted to show or hide Search form if the user is in the index view.

Try with below codes :

@if ("Index".Equals(ViewContext.RouteData.Values["Action"].ToString()))
{
    <form asp-action="Index" method="get" class="navbar-form form-inline navbar-right">
        <input class="form-control mr-sm-2" id="search" name="search" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" id="BtnSearch" name="BtnSarch" type="submit">Search</button>
    </form>
}
like image 148
Nan Yu Avatar answered Oct 07 '22 01:10

Nan Yu