To Implement Dynamic Parameters For
To Implement Dynamic Parameters For
NET MVC
application, you can follow these steps. This approach is especially useful for
cases like flexible searching, filtering, or sorting, where the parameters passed
to a stored procedure are dynamic.
For example, let's create a SearchEmployees stored procedure that will allow
filtering by Name and/or Position. These parameters are optional, so if no value is
passed, it will ignore the filter for that column.
sql
Copy
Edit
CREATE PROCEDURE SearchEmployees
@Name NVARCHAR(100) = NULL,
@Position NVARCHAR(100) = NULL
AS
BEGIN
SELECT *
FROM Employees
WHERE
(@Name IS NULL OR Name LIKE '%' + @Name + '%')
AND
(@Position IS NULL OR Position LIKE '%' + @Position + '%');
END
GO
In this procedure:
Here’s an example of how you could modify the repository method to call the
SearchEmployees stored procedure with dynamic parameters.
csharp
Copy
Edit
public class EmployeeRepository
{
private EmployeeDBEntities db = new EmployeeDBEntities(); // Your Entity
Framework context
csharp
Copy
Edit
public class EmployeeController : Controller
{
private EmployeeRepository repository = new EmployeeRepository();
// GET: Employee/Search
public ActionResult Search(string name, string position)
{
var employees = repository.SearchEmployees(name, position);
return View(employees);
}
}
This Search action allows you to pass name and position as query parameters in the
URL (e.g., /Employee/Search?name=John&position=Manager), and it will search
employees based on those parameters.
html
Copy
Edit
@model IEnumerable<MvcApp.Models.Employee>
<h2>Search Employees</h2>
<h3>Results</h3>
<table>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
@foreach (var employee in Model)
{
<tr>
<td>@employee.Name</td>
<td>@employee.Position</td>
<td>@employee.Salary</td>
</tr>
}
</table>
The form will send the parameters to the Search action, which then calls the
SearchEmployees method in the repository.
If the user searches for a name, it will only filter by that. If they search for
both name and position, it will filter by both.
5. Using the Dynamic Parameters in the URL
Now, if you navigate to /Employee/Search?name=John&position=Manager, it will show
employees whose name contains "John" and position contains "Manager".
You can also filter only by name or position by leaving the other parameter empty: