Making a button element submit - c#

Using ASP.NET, how do I make this button tag submit my ASP.NET form when clicked:
<button>Submit</button>
I'd like it to do a post back just like a regular asp.net server control button would work. I'd prefer a jquery way to do it if possible.

$('button').on('click', function(){
$(this).closest('form').submit();
});
On button click, it will find the closest form (which will be the parent) and submit it by passing the form to the action where you can access the values through your defined method; either get or post.
I think this is what you're asking.

You can either use:
<input type="Submit" />
Or using jQuery you can use:
$(function() {
$('button').on('click', function() {
$('form').submit();
});
});

you use javascript when you have links, or divs, or other elements that can not do post back.
In your case the <button>Submit</button> in html5 renders a submit button that if you click it, you just submit the form and that all you need.
The extra asp.net controls have some more functionality and communication with the code behind, but for the submit of the form, any submit button ether that one, ether the classic <input type="submit" value="Submit"> can do what you ask as they are.

Related

ASP.NET MVC: How do I change where Ajax.BeginForm will post to after the page loads?

I want to make an Ajax.BeginForm that will by default, go to the add user page. I also want in the same form an edit and delete button. The information in the form will be the same, I just need it to post to the different edit user and delete user URL.
How can I modify where the form will post, depending on what submit button is pressed, while keeping all the items that Ajax.BeginForm gives us.
Edit:
Also wanted to note that I want the URL to be generated by my routes. So in the same way the BeingForm uses the "action" and "controler" to make the path, I want to use that as well when I change the URL, so the URL is dynamic and not static.
I was able to get this to work by using jquery to change the action to the form using Url.Actions.
The HTML button:
<button type="submit" class="btn btn-danger" id="formDeleteButton" onclick="ChangeFormToDelete()">Delete</button>
The javascript/jQuery
function ChangeFormToDelete() {
$('#UserForm').attr('action', '#Url.Action("DeleteUser", "UserManagement")')
}
In #Url.Action the firstparameter is the action and the second is the controller. I made the exact same functions for edit and add and it worked perfectly.

Posting infomation in a textbox to another textbox on a different solution

Here is what I need to do (in ASP.NET):
Solution A, Project A, Page A will have a textbox and a link that opens up another page. This other page is part of Solution B, Project B, Page B. Page B will have a textbox and a submit button. When you click submit it will close the window returning to Page A placing the text that was in the textbox on Page B into another textbox on Page A.
I could probably store the value of the textbox into SQL Server and then retrieve it, but I was hoping there was another, better way.
Any help will be extremely helpful, thanks.
Using the following: ASP.NET, C#, JavaScript, jQuery, SQL Server, HTML, CSS, etc.
What if you use a jQuery modal window to display Page B and have a trigger within page B to send the data back to the element on page A
Page A:
<div id="page_a">
<form>
<input name="page_a_box" id="page_a_box">
</form>
</div>
<div id="container_for_page_b">
</div>
<script>
$.ajax({
url: 'page_b.asp'
,cache: false
,dataType: 'html'
,success: function(data){
// fill the container with html data
$('#container_for_page_b').html(data);
// invoke jQuery UI's dialogue window
$('#container_for_page_b').dialog();
}
});
</script>
Page B:
<div id="page_b">
<form onSubmit="$('#page_a_box').val($('#page_b_box').val()); $('#container_for_page_b').dialog('destroy');">
<input name="page_b_box" id="page_b_box">
<input type="submit" value="submit">
</form>
</div>
Check this out for more ideas:
http://jqueryui.com/dialog/#modal-form
I think you can easily achieve this by using query parameter's.
On Page B, during the Click event of the button, set a Session variable:
Session["TextBoxB"] = textBoxB.Text;
and then on Load in Page A, add the code to look for it:
if (Session["TextBoxB"] != null)
{
// it has a value so use it
textBoxA.Text = Session["TextBoxB"];
}

Can I move a div using javascript and retain its postback ability?

I've got a list of checkboxes and an ImageButton with an OnClick event in my page, clicking the ImageButton performs a postback and runs the OnClick event fine
The trouble is that I want to move the div to be the first child of the <form> so that I can make it appear in a modal window - I've done this using the prototype.js code...
document.observe("dom:loaded", function() {
if ($$('.CheckboxListContainer').length>0) {
var modalShadow = document.createElement('div');
modalShadow.setAttribute( "class", 'MyFormModalShadow' );
modalShadow.style.width = document.viewport.getWidth() + 'px';
modalShadow.style.height = document.viewport.getHeight() + 'px';
var modalDiv = document.createElement('div');
modalDiv.setAttribute( "class", 'MyFormModal' );
var checkboxesDiv = $$('.CheckboxListContainer')[0];
checkboxesDiv.remove();
modalDiv.appendChild( checkboxesDiv );
$$('form')[0].insert( {top: modalShadow} );
$$('form')[0].insert( {top: modalDiv} );
Event.observe(window, "resize", function() {
if ($$('.MyFormModalShadow').length>0) {
var modalShadow = $$('.MyFormModalShadow')[0]
modalShadow.style.width = document.viewport.getWidth() + 'px';
modalShadow.style.height = document.viewport.getHeight() + 'px';
}
});
}
});
... which works fine, but the ImageButton is no longer triggering my OnClick event on postback.
Is there a way to move my div around in the DOM and retain its postback abilities?
Quick answer, yes. Long answer below:
If you're talking ASP.NET WebForms, does your form have the runat="server" attribute and an id? If you're using standard HTML, are the method and action attributes set on the form?
When you look at the HTML source in your browser, if the form looks like: <form action="/your_post_back_page.html" method="post">, then that's all good. Inspect the form with FireBug after the modal dialog has been added, see if it is INSIDE the form tags. If so, that's good.
Do your check boxes <input type="checkbox" /> have a name attribute set? Is your image button <input type='submit' /> or is it a <button>?
If these conditions are met, then there is probably a JavaScript event (a function) wired to your button that is returning false and/or swallowing the postback. JavaScript onclick events generally need to return true to submit a form. Is there any output in your browser's error console?
Personally, I find more and more that pure HTML (by way of ASP.NET MVC) beats the pants off old school ASP.NET WebForms, and jQuery has, in my experience, a far nicer feel than prototype. Using jQuery templates to create a modal dialog would be easy. Can you swap libraries?
First of all, i am not very clear why you need to move the element to be the first child of the form to make it modal. You can make any div modal no matter where is the position in the form. The most important think is controlling the absolute positioning properly.
Each postback gets triggered by a __DoPostBack() javascript function, so you should not have any issues with moving the control around, unless you changed the id of the control.
One possible solution to your problem is calling the __DoPostBack() function from your client code in document.ready, and that way you have full control over the form submission.

type submit vs type button

I have a button which right now is set as a type "submit". This calls the controller, execute some code and returns back to the view. When I use jquery to hide the button, I see that when I click on the button, what I have hides the button but as soon as the view is returned, the button is not hidden no more. Whereas with type "button", when I click the button, this hides the button but doesnt execute the code in the controller. Is there a way to hide the type "submit" button so when the view returns, the button is still hidden?
$('#btnAdd').click(function() {
$('#btnAdd').hide();
});
<input type='submit'> creates a button that submits a form to a server and triggers your server code. If you want the button hidden when the page comes back, you need to add logic to your page to do that. How you do this will depend on your server technology (php, .net, etc.).
The reason the behavior with <button> is different is that <button>s don't submit the form (unless you add more code to make them do that)...so the above mentioned stuff never happens. It's not so much that a <button> stays hidden as much as the page never changes/reloads. If you added code to the <button> to make it refresh the page, it'd reappear, too.
The button is shown because the page is newly displayed after submiting the form. Your "old" page, where clicked and hid the button is history.
What do you want?
Pressing a button, do something on serverside, do not change your current page:
Use a button of type button, use ajax to call the server side.
Or use a button of type submit and do what Pablo said http://en.wikipedia.org/wiki/Post/Redirect/Get on serverside.
Pressing a button, do something on serverside, give user feedback:
Use <form method="post" to markup your form. Use a submit button to call the server side. On serverside hide the submit button, if it is called by method post (calling a page with link or typing it into the address field is calling it with method = get).
What is the difference between type submit and type button?
A submit button works without javascript to send some input to serverside. The surrounding form is send to the server and the response is rendered in browser.
A button button needs a javascript onclick handler, a javascript function. The onclick handler is called when the user pressed the button.
Since the page will be reloaded upon pressing the submit button, the button will reappear. One quick and dirty to get what you want is...
First, create a hidden field
<input type="hidden" id="hidden" value="" />
Then, when you press submit, in a click event for submit button, do something like this..
$('#submit').click(function() {
$('#hiddenField').val("1");
$('#form').submit();
return false;
});
Now in your controller, use the value of hiddenField of pass some variable to the view which can be used like this...
<?php if($hidden == "1"): ?>
<input type="submit" id="submit" value="Submit" />
<?php endif; ?>
As far as the button not submitting the form is concerned, it won't submit the form, until you submit the form yourself on the click event of button. Something like this...
$('button').click(function() {
$('#form').submit();
});
Of course, as I mentioned this is a quick and dirty way to implement the function you want, there are better ways - using AJAX, also the implementation can change depending on what server side language you use (I used php over here).
When your form is submitted and your controller process the data, if certain criteria is met, you can set a temporary session variable or a cookie in server side code. So, basically the page will check for this variable on every page load. Example in PHP:
if( empty($_SESSION['temp']['hideSubmitButton']) ) {
$submitButton = '<button type="submit">Normal Button</button>';
} else {
$submitButton = '<button type="submit" disabled="disabled">Disabled Button</button>';
// or $submitButton = '';
}
But then you have to decide when to unset() the $_SESSION['temp'] or $_COOKIE['temp'] variable.

Handing forms in ViewUserControls

I am rendering out a ViewUserControl (.ascx file) in a view:
<% Html.RenderPartial("Comments", Model.Comments); %>
This ViewUserControl shows associated comments on an entry. I would like this control to render out a form as well, so users of my application can contribute.
How would you add a form to a ViewUserControl and handle it's postback?
Just add the form in there the same as you would on any page. In MVC, the form does not postback as such - it simply submits itself and its content (input controls) via HTTP Post to a URL.
Simply create an action in your controller (and hence a URL) which the form will post and do whatever activity is required there...
There is no postaback, like in standard asp.net, there can be only form tag that posts data to some url (controller/action).
Inside your partial user control, write:
<form action="controller/actionname" method="post">
<input type="text" name="inputText" />
<input type="submit" value="Post data to server" />
</form>
In MVC, only input type="submit" triggers form submit. In standard ASP.NET webforms, you can have many Linkbuttons, Buttons, ... but under cover, they all triggers this simple click on input type="submit" through javascript event. One form can post data to only one URL (controller/action), but that can be changed with javascript (as we can see in html source of 'old' asp.net webforms).
then, in controller you can handle post data:
[AcceptVerb(HttpVerb.Post)] // optionally
public ActionResult ActionName(string inputText) ...
Like others have answered already, you simply render a form and handle it's submit with an ActionResult.
For example, if your form (which could be rendered anywhere in your site) was submitting to http://www.yoururl.com/home/save, you would create an ActionResult method named save on the home controller to handle the submit (likely post/get method).

Categories

Resources