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:
How Search
action looks like in almost all controllers:
The problem:
When I write a value to search about and after submitted the form it goes to a false Route
and 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
?12 Replies
The Partial view:
You could make it so that on the submit of the search form it sends a string values of the area/controller it needs to go to. These could be hidden inputs.
??????????
Lemme re-write the action, on my phone so bare with
ok, thanks in advance
Think you can use:
return RedirectToRoute(new
{
area= “”,
controller = "",
action = "",
model = model
});
Rather than the form only submit the search query. Have it post a model that contains the search query, area and controller name.
where should I put this piece of code?
Replace your: return View(model)
With the return redirect to view code
public class SearchViewModel
{
public string Query { get; set; }
public string Controller { get; set; }
public string Area { get; set; }
}
That can be your model
but the issue is not in the
Controller
, the issue is in the _SearchBox
PartialView
Have you got the area attribute named on each of the controllers?
yeah
Then I think you need to rename the http on the a search action to this:
Remove the area and controller bit on the http attribute as I’m pretty sure that’s what’s causing the confusion