C#C
C#4y ago
M B V R K

How to set the `Area` and `Controller` dynamically in a form of a `Partial View` ?

Hello friends, I'm working on an Asp.Net core 6 project, with Areas.
I have created a PartialView, this partial view is created for Search it contains an Input element which will contain the value that the user wrote in, and after submit this form will send that value to an Action called Search in the controller.
I want this partial view to work generically, which I can use it with any view and during the submit the partial view should send that value to the Action called Search in the current Controller.

As you see the Action will be fixed because it is known, but the Controller is unknown because it is dynamically changing.

An example of using this partial view:
  <div class="card card-preview">

        <div class="card-inner">

            @{
                await Html.RenderPartialAsync( "_SearchBox" );
            }
            
            <br>
// The rest of the view


How Search action looks like in almost all controllers:
        [HttpGet("/[area]/[controller]/Search/{value}")]
        public async Task<IActionResult> Search(string value)
        {
            var response = await _mediator.Send( new SearchStudentAbsencesQuery( value ) );
            var model =  _mapper.Map<List<StudentAbsenceIndexVm>>( response.Entities );

            ViewBag.SearchValue = value;
   
            return View( model );
        }


The problem:
When I write a value to search about and after submitted the form it goes to a false Routeand that route is not found
like this https://localhost:44302/Controller/Search
As example let's assume that we are in a controller called StudentAbsences when I submit that search it goes to that false route https://localhost:44302/StudentAbsence/Search which need before the controller the Area name.

My Question:
How I can make that PartialView to automatically/dynamically know the Controller and the Area ?
Was this page helpful?