-1

I have searched on stackoverflow and google and have found many articles on the subject but I still can't seem to know what I am doing wrong! I really feeling desperate. E.g. How to handle two submit buttons on MVC view

I'm just trying to have three buttons in my view. I do hit the action in the controller, however, the string comparison does not work. For some reason, I cannot hit my breakpoints.

Here's my code: View:

@using RequestDB7mvc.Models
@model MainViewModel
@{
    ViewBag.Title = "Main";
}
<div class="form-group">
@using (Html.BeginForm("Search4", "Requests", FormMethod.Post))
{
    <input type="submit" value="Save" name="command" />
    <input type="submit" value="Done" name="command" />
    <input type="submit" value="Cancel" name="command" />
}

Controller:

[HttpPost]
public ActionResult Search4(MainViewModel model, string command)
{
    if (command.Equals("Save"))
    {
        // Call action here...
        string f = "break";
    }
    else if (command.Equals("Done"))
    {
        // Call another action here...
        string f = "break";
    }
    else if (command.Equals("Cancel"))
    {
        // Call another action here...
        string f = "break";
    }

    ViewBag.Msg = "Details saved successfully.";
    return View();
}
Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
Nearshore
  • 149
  • 3
  • 15
  • Did you try and debug as to what you are getting in the command parameters in the action. If you cannot hit breakpoint, try writing to trace and verify – Shahzad Aug 04 '17 at 13:37
  • I did try. And I see the command value, e.g."Cancel". However, it does not jump into the if statement :-( – Nearshore Aug 04 '17 at 13:40
  • try command.Equals("Cancel", StringComparison.InvariantCulture) – Shahzad Aug 04 '17 at 13:45
  • Thank you. I tried. Didn't work. Can I attach a picture here? Here is the debugger screenshot: http://imgur.com/OKmSJTF – Nearshore Aug 04 '17 at 13:59
  • @Nearshore how do you send MainViewModel model, string command values in your request. I couldnt see any form input data in question? – hasan Aug 04 '17 at 15:06

1 Answers1

0

You just need to add command into your Model.

public class MainViewModel
{

    ...

    public string command { get; set; }

    ...
}

Then in your controller, remove the command parameter and handle from the model:

public ActionResult Search4(MainViewModel model)
{
    if (model.command.Equals("Save"))
    {
        // Call action here...
        string f = "break";
    }
    else if (model.command.Equals("Done"))
    {
        // Call another action here...
        string f = "break";
    }
    else if (model.command.Equals("Cancel"))
    {
        // Call another action here...
        string f = "break";
    }

    ViewBag.Msg = "Details saved successfully.";
    return View();
}
Ashley Medway
  • 7,151
  • 7
  • 49
  • 71