Vüsal Mammadli
Vüsal Mammadli

Reputation: 3

Using two different buttons on the controller in ASP.NET MVC

I have an ASP.NET MVC project. In this project, I have a controller named MessageController. I have 2 methods in this controller, one is HttpGet and the other is HttpPost.

I want to run an operation like this in my method with HttpPost attribute. If the first button in the view is clicked, it will be an operation, if the second button is clicked, it will be another operation.

How can I do this operation?

Here is my code:

public class MessageController : Controller
{
    MessageManager mg = new MessageManager(new EfMessageDal());

    [HttpGet]
    public ActionResult NewMessage()
    {
        return View();
    }

    [HttpPost]
    public ActionResult NewMessage(Message p)
    {
        MessageValidator messagevalidator = new MessageValidator();
        ValidationResult result = messagevalidator.Validate(p);

        if (result.IsValid)
        {
            if (//clicking button1)
            {
                //operate first operation
            }
            else
                //operate second operation
        }
        else
        {
               //Error Messages
        }

        return View();
    }
}

Upvotes: 0

Views: 45

Answers (1)

benuto
benuto

Reputation: 292

  1. if you want to use single endpint NewMessege, then you have to add parameter (button name, additional value) and bind it with buttons. Then you resolve target method by this parameter. That new parameter can be wrapped with post model
public class MessagePostModel
{
   public Message Message {get;set;}
   public int ButtonId {get;set;}
}
  1. Another option is to add a third post method to the controller. Each button calls its own endpoint where you call specific operations

Upvotes: 1

Related Questions