1

I've got a view with multiple submit buttons, and I don't know what the best way to handle this is. At the moment one of my controller actions looks like this:

[HttpPost]    
public ActionResult SaveAlbum(
    string saveButton,
    string createButton,
    string deleteButton,
    string showButton,
    string myHiddenValue)
{
    if (!String.IsNullOrEmpty(saveButton))
    {
        // do stuff
    }

    if (!String.IsNullOrEmpty(createButton))
    {
        // do stuff
    }

    // repeat for all buttons

    var viewModel = new MyViewModel(one, two, three);

    return View("Index", viewModel);
}

This looks pretty terrible. I'm assuming the best way would be to have a separate form for each submit button, which posts to different actions, but as it only posts what's inside the form and I need myHiddenValue for all of them I don't know what I should do. Should I use multiple hidden values instead? The hidden value is a comma separated list of values for all the checked checkboxes (added with jQuery).

2

3 Answers 3

1

Ideally all your submits should go to individual Action methods on controller.

[Update] A quick search on stackoverflow gives following links:

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, like I said that's what I assume but I don't know what to do when I need the hidden value for each of them. I updated the title of my question so it's clearer.
Ideally, any submit action on the form should submit entire form. So you should get it. I don't have any working sample for the same though.
0

It's easy

suppose you have two buttons

 <input type="button" name="btnSave"  value="Save"/>
 <input type="button" name="btnSave"  value="Update" />

your controller

  public ActionResult SaveAlbum(string btnSave)

if u click on Save, value of btnSave will be "Save" and if u click on Update button, value of btnSave at controller will be "Update". so give the save name to all your button but different values.

3 Comments

This would still mean only one controller action and I'd have to check for the value of the button to know what code to run.
you can redirect from controller to your desired action after checking the value.
and if you want to redirect directly from view then you have to write script and change then action of your form.
0
$('#btnUpdate').click(function(){
   e.preventDefault();
   $(form).attr("action", "Update");
   $(form).submit();
});

public ActionResult Update(string btnSave)

$('#btnSave').click(function(){
   e.preventDefault();
   $(form).attr("action", "Save");
   $(form).submit();
});

public ActionResult Save(string btnSave)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.