razor/ ASP.NET Web Pages multiple buttons - c#

I have two buttons in the same page ( Razor/ ASP.NET Web Pages), how do I check which button I clicked,
so far I have:
if (IsPost)
{
//code block here
}
<input type="submit" value="Update" class="submit" id="btnUpdate" />
<input type="submit" value="Clear" class="submit" id="btnClear" />
the problem is (my low IQ, I know) it executes with any button clicked, only btnUpdate should execute the code block
Note: IS NOT MVC
note2: asp.net shows an example checking which textbox is empty to determine the action when a different button is clicked, is not what I'm looking for

<input type="submit" value="Update" class="submit" id="btnUpdate" name="update" />
<input type="submit" value="Clear" class="submit" id="btnClear" name="clear"/>
attach name attribute to buttons and check which one submitted via
if(IsPost){
if (Request.Form["clear"] != null)
{
//when clear clicked
}
else if (Request.Form["update"] != null)
{
//when update clicked
}
}

Please try this:
if (IsPostBack)
{
if(! string.IsNullOrEmpty(Request.Form["Button2"]))
Response.Write("{Button2 was clicked");
}

remove the "submit" class from your clear button, and change its type to "button"
. This will prevent it from posting the form.

Related

Asp.Net unable to fire event on button click

I'm new to ASP.Net. I am trying to trigger action based on button click but the even is not getting triggered.
This is the button definintion in login.aspx:
<button type="submit" value="submit" class="btn_3" onclick="createAccount_Clicked" runat="server">
Create Account
</button>
This is the intended button click event inside login.aspx.cs:
protected void createAccount_Clicked(object sender, EventArgs e)
{
//Here's where you do stuff.
string value = new_fullname.Value.ToString();
}
new_fullname is the Text I'm trying to read (defined in login.aspx):
<div class="col-md-12 form-group p_star" runat="server">
<input type="text" class="form-control" id="new_fullname" name="name" value=""
placeholder="Full Name" runat="server">
</div>
So, you have set the button type to submit which actually submits the server form which does not guarantee the triggering of the intended event. What you should do is, set the button type to button to get it working.
This is how you will get it working:
<button type="button" value="submit" class="btn_3" onclick="createAccount_Clicked" runat="server">
Create Account
</button>

On postback, how can I check which html button cause postback in code behind

On postback, how can I check which html button cause postback in code behind
<button type="submit" name="index" class="btn" />
<button type="submit" name="index" class="btn" />
<button type="submit" name="index" class="btn" />
You will have to change your markup if you would like to know which button caused a postback, so that each button has a unique name ( right now they all have the same name).
In addition,you must provide a value for each button in order to check which button posted back.
Also, it's recommended to provide an id, but in your situation you could still get to know which button caused postback without providing an id.
Markup recommended for your scenario
<form id="form1" runat="server">
<div>
<button type="submit" name="index1" class="btn" value="Button1">Button 1</button>
<button type="submit" name="index2" class="btn" value="Button2">Button 2</button>
<button type="submit" name="index3" class="btn" value="Button3">Button 3</button>
</div>
</form>
C# code to check which button posted back
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
if(Request["index1"] !=null)
{
//then first button posted back
//Request["index1"] will return the value property of the button index1 if it posted back
} else if(Request["index2"] !=null)
{
//then first button posted back
//Request["index2"] will return the value property of the button index2 if it posted back
} else if(Request["index3"] !=null)
{
//then first button posted back
//Request["index3"] will return the value property of the button index3 if it posted back
}
}
}

how to create two buttons within form and have only one submit form

I am trying to create a "next" button and a "back" button in my form. I want the "next" button to validate and submit the form. And I want the "back" button to simply go back to the "cart" page. But the "back" button keeps validating and trying to submit the form.
Here is my code:
<div class="buttons">
<button class = "button" id = "back">Back</button>
<input type="submit" value="Next" class="button" />
</div>
The reason I need the back link to be a button is so that it will look the same as the "next" button. Any ideas how I can get this working correctly?
A <button> element always submits the form. The same goes for a <input type="submit" /> element.
But a <input type="button" /> will not submit the form. That's what you want.
<div class="buttons">
<input type="button" class="button" id="back" onclick="window.location = '#Url.Action("Index", "Cart")';">Back</a>
<input type="submit" value="Next" class="button" />
</div>
Edit I'm not sure if you can put that inside an <a> element though. I reworked my example to use click events rather than a link. If it is valid to put inside a <a> element (can anyone confirm?), you can do it like that as well.

Cancel button in form

I have a cancel button in a form:
#using (Html.BeginForm("ConfirmBid","Auction"))
{
some stuff ...
<input type="image" src="../../Content/css/img/btn-submit.png" class="btn-form" />
<input type="image" src="../../Content/css/img/btn-cancel.png" class="btn-form" />
}
The issue is I want this button to go to a particular view when I click on it. How do I do this?
Either you can convert the Cancel button as an anchor tag with #Html.ActionLink helper method and apply a css class which makes the link to looks like a button and then in the controller action for that link, you can return the specific view.
#Html.ActionLink("Cancel","Index","Products",null, new { #class="clsButtonFake"})
or
Use 2 submit buttons in the form. One for real submit and one for the cancel. and in your controller action, check which button called the action method.
You can read more about it here in this answer.
Lot of the answers worked in either of the browsers, chrome or ie but not all.
This worked in all -
<input type="button" value="Cancel" onclick="location.href='#Url.Action("Index","Home")';"/>
This is my button HTML:
<button type="button"
class="btn btn-inverse"
id="cancel"
onclick="window.history.back()">
<i class="icon-remove icon-large"></i>
<br />#Localization.Cancel
</button>
Then to customize the onclick attribute in some views I do this:
<script>
$(document).ready(function ()
{
$("#cancel").
attr("onClick",
"document.location.href='#Html.Raw(Url.Action("Index", "Standard",
new { ManualId = Model.ManualId, ChapterId = Model.ChapterId }))'");
});
</script>
Or a styled submit button:
<input type="submit" value="Save Form" name="Save" class="submit-button btn-form" />
Then Javascript for cancel button:
<input type="button" onclick="document.location.href('Home/Index')" value="Cancel" class="cancel-button btn-form" />
// Note: This avoids any of the validation that may happen in the model that
// normally gets triggered with a submit
So with Shyju's appraoch, you use the built in MVC ActionLink helper. Doing this, you'll need to have any images or icons done through css. However, this is much more cachable, especially if you use base64 strings for your images in css.
I like Adauto's approach because it gives you much more control of the markup. MVC Html Helpers are nice, but they still seem to have their heads in the WebForms mindset of "don't worry about it, we'll take care of it for you".
The one thing I would add is Url.Content.
<img src="#Url.Content("~/Content/css/img/btn-submit.png" class="btn-form" />
It's never really a good idea to make your views have to know the location of content relative to it's location.
<a href="/Auction/[ActionName]">
<input type="image" src="#Url.Content("~/Content/css/img/btn-cancel.png")" class="btn-form" />
</a>
if you want to preserve its look as a button, you could do something like this:
<a href="/Auction/[ActionName]">
<input type="button" value="Cancel">
</a>
where [ActionName] is the name of the action that will return your desired view.
<img src="../../Content/css/img/btn-submit.png" class="btn-form" />
I ended up making a helper so I could reuse the cancel button. I added a js confirm in case people click the cancel button by accident after filling in the form.
#helper FormCancelButton(string cancelUrl)
{
<button type="button" class="btn" onclick="if (confirm('Cancel changes?')) location.href = '#cancelUrl';">Cancel</button>
}
I then call it like so:
#FormCancelButton(Url.Action("Index", "User" ))
If you are really keen you could try and detect the dirty state of the form too and only show the confirm dialog if the form had been changed.
<asp:Button runat="server" class="btn btn-danger"
CausesValidation="false" onclick="Cancel_Click" Text="Cancel"/>
protected void Cancel_Click(object sender, EventArgs e)
{
Response.Redirect("Test.aspx");
}

Does ASP.NET MVC swallow submit values?

I have a single form in ASP.NET MVC (v1) that has 2 input buttons. Each submit button has to be contained within this single form and I need to know which one the user pressed.
I know about the trick to check the FormCollection values which will be returned based on the button pressed. For example, if I have and and the user clicks Button2, I should be able to say Request.Form["Button2"] != null and that will evaluate to true in which case I know that the user clicked that button.
However, this is not working for me. The values of all my buttons is null as non of them are contained within the Request.Form values. Is there a bug in ASP.NET MVC which swallows these values?
Here is my form code:
<% using (Html.BeginForm()) {%>
<% Html.RenderPartial( "EditAreaControl", Model ); %>
<div class="form-layout-command-container">
<div class="form-layout-command-area-alpha"><button type="submit" name="submit1" value="Save">Save</button></div>
<div class="form-layout-command-area-alpha"><button type="submit" name="submit2" value="SaveAndCopy">Save and Create Copy</button></div>
<div class="form-layout-command-area-beta"><%= Html.ActionLink("Cancel", "list") %></div>
</div>
<% } %>
Here is my controller code:
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Add(FormCollection values )
{
if (values["submit1"] != null)
// always false
if (values["submit2"] != null)
// always false as well
}
From w3schools:
Important: If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the and tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.
It seems that this is not standardized. You should stick to
<input type="submit" name="submitButton" value="Save" />
<input type="submit" name="submitButton" value="Cancel" />
I would use inputs of type submit instead of buttons. Non-inputs may not passed back in a form post or at least can be passed back inconsistently. Note that they can have the same name with different values so that you can use the same parameter for any button that submits the form.
<input type="submit" name="submitButton" value="Save" />
<input type="submit" name="submitButton" value="SaveAndCopy" />
public ActionResult Save( string submitButton, ... )
{
if (submitButton == "Save")
{
...
}
else if (submitButton == "SaveAndCopy")
{
...
}
....
}
Using Firebug, I found that the submit buttons were not being sent in the response and because of that, there isn't much I can do on the MVC side. I decided to use a client side hack to populate a hidden input field on the client side which would be passed to the controller values.
I changed the input buttons to be:
<input type="submit" value="Save" onclick="actions.copyValues($(this), $('#submitAction'));" />
<input type="submit" value="Save and Copy" onclick="actions.copyValues($(this), $('#submitAction'));" />
<input type="hidden" id="submitAction" name="submitAction" />
The jquery script simply copies the values:
Actions.prototype.copyValues = function(from, to) {
$(to).val($(from).val());
};
The controller action then looks for the hidden input values:
var request = HttpContext.Request;
return request.Form["submitAction"];
This solves the issue from above but I realize it is not that clean.
Put them in two different forms and you will know which one submitted based on which action was called on the controller.

Categories

Resources