Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's an extension method I wrote to handle multiple image and/or text buttons.</p> <p>Here's the HTML for an image button:</p> <pre><code>&lt;input id="btnJoin" name="Join" src="/content/images/buttons/btnJoin.png" type="image"&gt; </code></pre> <p>or for a text submit button :</p> <pre><code>&lt;input type="submit" class="ui-button green" name="Submit_Join" value="Add to cart" /&gt; &lt;input type="submit" class="ui-button red" name="Submit_Skip" value="Not today" /&gt; </code></pre> <p>Here is the extension method you call from the controller with <code>form.GetSubmitButtonName()</code>. For image buttons it looks for a form parameter with <code>.x</code> (which indicates an image button was clicked) and extracts the name. For regular <code>input</code> buttons it looks for a name beginning with <code>Submit_</code> and extracts the command from afterwards. Because I'm abstracting away the logic of determining the 'command' you can switch between image + text buttons on the client without changing the server side code.</p> <pre><code>public static class FormCollectionExtensions { public static string GetSubmitButtonName(this FormCollection formCollection) { return GetSubmitButtonName(formCollection, true); } public static string GetSubmitButtonName(this FormCollection formCollection, bool throwOnError) { var imageButton = formCollection.Keys.OfType&lt;string&gt;().Where(x =&gt; x.EndsWith(".x")).SingleOrDefault(); var textButton = formCollection.Keys.OfType&lt;string&gt;().Where(x =&gt; x.StartsWith("Submit_")).SingleOrDefault(); if (textButton != null) { return textButton.Substring("Submit_".Length); } // we got something like AddToCart.x if (imageButton != null) { return imageButton.Substring(0, imageButton.Length - 2); } if (throwOnError) { throw new ApplicationException("No button found"); } else { return null; } } } </code></pre> <p><strong>Note:</strong> For text buttons you have to prefix the name with <code>Submit_</code>. I prefer this way becuase it means you can change the text (display) value without having to change the code. Unlike <code>SELECT</code> elements, an <code>INPUT</code> button has only a 'value' and no separate 'text' attribute. My buttons say different things under different contexts - but map to the same 'command'. I much prefer extracting the name this way than having to code for <code>== "Add to cart"</code>. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload