Example to handle multiple submit buttons in ASP.NET MVC Framework

ASP.NET MVC is a popular web framework that follows the Model-View-Controller (MVC) architectural pattern. It provides a flexible way to build web applications using C# or any other .NET language. In an MVC application, it's common to have multiple forms on a page that contain submit buttons. In this blog post, we'll discuss how to handle multiple submit buttons in ASP.NET MVC.

## The Problem

Consider a scenario where you have a page with two forms. Each form has its own submit button. When a user clicks on one of the submit buttons, you want to perform a specific action based on which button was clicked. For example, one form may be used to update a user's profile, while the other form may be used to upload a file.

In traditional HTML forms, when a user clicks on a submit button, the entire form is posted to the server. The server then handles the request and sends a response back to the client. However, in an MVC application, you may want to perform different actions depending on which submit button was clicked. This is where the problem arises.

## The Solution

To handle multiple submit buttons in ASP.NET MVC, we can use the name attribute of the submit button. By assigning a unique name to each submit button, we can determine which button was clicked when the form is posted to the server.

Here's an example:

    
    
    
    

    
    
    

In this example, we have two forms. Each form has a submit button with a unique name (submitButton) and value (updateProfile and uploadFile). When the user clicks on one of the submit buttons, the form is posted to the server with the value of the clicked button.

In our controller, we can retrieve the value of the clicked button using the FormCollection object:
[HttpPost]
public ActionResult ProcessForm(FormCollection form)
{
    var buttonValue = form["submitButton"];

    if (buttonValue == "updateProfile")
    {
        // Update user profile
    }
    else if (buttonValue == "uploadFile")
    {
        // Upload file
    }

    return View();
}
In this code, we retrieve the value of the clicked button from the FormCollection object. We then use a conditional statement to determine which action to perform based on the button value.

## Conclusion

Handling multiple submit buttons in ASP.NET MVC is a common requirement. By using the name attribute of the submit button, we can determine which button was clicked and perform the appropriate action. This approach allows us to build flexible and interactive web applications with ease.
 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
7 + 5 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice