ASP.NET MVC - several buttons on the form

I would like to have several buttons in the form of images in this form:

<% Html.BeginForm("Create", "Foos", FormMethod.Post); %> <!-- html form elements --> <%=Html.SubmitImage("Button", "save-button.gif", new { alt = "Save" })%> <% Html.EndForm(); %> 

I read about Html.ActionImage, but I do not see it in Microsoft.Web.Mvc, I think it was deleted, is there any other way to add buttons?

I would like to save, delete, publish, cancel, etc. buttons in one form, as images, preferably each of which causes its action in the controller.

+4
asp.net-mvc
source share
2 answers

You can use a good ole html:

 <input type="button" name="CancelButton" id="CancelButton" value="Cancel" /> 

or

 <button name="CancelButton" id="CancelButton">Cancel</button> 

or one of the assistants

 <%= Html.Button("CancelButton", "Cancel", "MyJavascriptFunction()") %> 

In any case, you probably need to write a little javascript if you just don't want to use the link to cancel.

Here is a little blog entry about assistants.

+1
source share

One option is to have separate shapes for each button. This is often impossible or easy without Javascript or garbled HTML. This makes it easy to send each request to a different action method.

This is a solution that I developed for a few image submit buttons. I am not particularly happy with this, but it works and can be easily reorganized later if an alternative is built into the structure.

In your HTML:

 <%= Html.SubmitImage("Dog", "~/images/dog.jpg")%> <%= Html.SubmitImage("Cat", "~/images/cat.jpg")%> 

In the controller action method for the form:

(This is an action method. It's up to you how to implement each button)

  public ActionResult Index(FormCollection form) { // get the name of the button that was clicked (sent via either Dog.x or Cat.x since its an image button) var buttonName = form.GetSubmitButtonName(); if (buttonName == "Remove" || buttonName == "Skip") { Remove(form); } else if (buttonName == "Add") { Add(form); } } 

Extension Method:

(Here we found a form parameter called Remove.x or Skip.x or Add.x and removes the .x part)

 public static class FormCollectionExtensions { public static string GetSubmitButtonName(this FormCollection formCollection) { var button = formCollection.Keys.OfType<string>().Where(x => x.EndsWith(".x")).SingleOrDefault(); // we got something like AddToCart.x if (button != null) { return button.Substring(0, button.Length - 2); } throw new ApplicationException("No image button found"); } } 

Note. One alternative is to use CSS to place the background image on a regular type of Html.SubmitButton button (a regular HTML button instead of an HTML image button), but I did not find it satisfactory for me because of the different ways different browsers behave ( see this question ).

0
source share

All Articles