In ASP.NET MVC, handling multiple submit buttons in a form is straightforward. I'll guide you through it using an example where we're posting employee details and product details.
First, in my view, I'll create a form with two submit buttons, each with a different name. One button will be for adding employee details, and the other will be for adding product details.
@using (Html.BeginForm("AddOrUpdate", "MyController", FormMethod.Post))
{
<label for="employeeName">Employee Name:</label>
@Html.TextBoxFor(model => model.EmployeeName)
<button type="submit" name="addEmployee">Add Employee</button>
<label for="productName">Product Name:</label>
@Html.TextBoxFor(model => model.ProductName)
<button type="submit" name="addProduct">Add Product</button>
}
In my controller, I'll have an action method called AddOrUpdate to handle the form submission. In this method, I'll inspect the values of the submit buttons to determine which action to take.
[HttpPost]
public ActionResult AddOrUpdate(EmployeeViewModel employee, ProductViewModel product, string addEmployee, string addProduct)
{
if (!string.IsNullOrEmpty(addEmployee))
{
// Handle adding employee
// For example:
// employeeService.AddEmployee(employee);
return RedirectToAction("EmployeeList");
}
else if (!string.IsNullOrEmpty(addProduct))
{
// Handle adding product
// For example:
// productService.AddProduct(product);
return RedirectToAction("ProductList");
}
// Default action if neither button is clicked
return View();
}
In this action method, I'm checking the values of the addEmployee and addProduct parameters. Depending on which button was clicked, I'll handle adding employee details or product details accordingly.
That's it! With this setup, I can handle multiple submit buttons in ASP.NET MVC and post employee and product details from the same form. // EmployeeViewModel.cs
public class EmployeeViewModel
{
public string EmployeeName { get; set; }
// Add more properties as needed for employee details
}
csharp
Copy code
// ProductViewModel.cs
public class ProductViewModel
{
public string ProductName { get; set; }
// Add more properties as needed for product details
}
These view model classes represent the data that will be sent from the form to the controller action method.
You can add more properties to these classes for additional details about employees and products, or you can use your custom
I have provided this to serve as an example.