Save and retrieve checkbox values asp.net mvc - asp.net

I'm new to asp.net mvc and currently using MVC 2. I'm struggling with working with checkboxes for days now. I simply need to get checked checkbox values to be saved in database and on Edit view check them back.
<input type="checkbox" id="coduit for safety near motor" name="Prepration" value="coduit for safety near motor"/><br />
<input type="checkbox" id="coduit for far side safety" name="Prepration" value="coduit for far side safety"/><br />
<input type="checkbox" id="coduit for power cable to near power point" name="Prepration" value="coduit for power cable to near power point"/><br />
On post controller method i can save the values of checked Checkboxes to the database as a comma separated string by using
strign a= = Request.Form["Prepration"];
How can i show them back on Edit view?
I don't know whether this is the way to do this any alternative solution would be great

The answer of your first question:
Need to get checked checkbox values to be saved in database
On a button click push all the values in a array and from there store them in a hidden field and when you post your form get those values from this hidden field:
<script type="text/javascript">
$(document).ready(function () {
$("input#btnSubmit").click(function () {
var id = [];
$("input[name='Prepration']:checked").each(function () {
id.push($(this).val());
});
$("#HiddenFieldId").val(id);
});
});
</script>
Now coming to your second question:
How can i show them back on Edit view?
<input type="radio" id="a" name="Prepration" checked="#Model.BoolPropertyName" />
Here you can have the value of in boolan.
Hope this will help you.

you can client side solution,
var data="";
$.each($("input:checkbox"),function(){
if($(this).is("checked")){
data+= $(this).val();
}
});
// post here

Related

GWT - Get the value of a checkbox from a servlet [duplicate]

I have an html form and i would like ALWAYS to have checkboxes to submit a value. How can i do that? I have one idea but i havent tried it and i am unsure if its the best way to do it (jquery to check if the box is checked or not, then set the value to 0/1 and check it off so it will submit)
Thanks to #Lazarus' idea, also mentioned by #BalusC, you can add an additional control to the form:
<input type="hidden" name="checkbox1" value="off">
<input type="checkbox" name="checkbox1" value="on"> My checkbox
Checkbox and the hidden fields must have the same name. The hidden input is always submitted as a default value. If the checkbox is checked then also it's submitted. So you have a list of 2 values for parameter "checkbox1", that you have to treat at server side.
...maybe a <select> tag would be more handy.
There is a legitimate reason for asking for something like this, although the behaviour envisioned here is not the right way to go about it. There is a problem with the checkbox when used correctly when editing existing data and that's that there is no way to determine whether no value was submitted because the field was not present on the form or because the user cleared all of the values. You can run into this sort of problem any time you include fields conditionally.
One could go to the trouble of maintaining a "view state", of course, but it's much easier to include a hidden "companion field" whenever a checkbox or select with the multiple option (which is also excluded when all selections are cleared) is displayed. The field should have a related but different name (a name from which the actual field name can be extracted). The Lotus Domino server has used fields named %%Surrogate_FieldNameHere for this purpose since (I believe) version 7 for exactly the reason I described here.
To tell you the truth, this feels like a big no-no.
Anyway here goes:
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function () {
$(this).attr('value', $(this).is(':checked') ? '1' : '0');
$(this).attr('checked', true);
});
});
});
</script>
HTML doesn't work that way. HTML checkboxes are specified as follows: if checked, then its name=value will be sent as request parameter. If unchecked, then its name=value will not be sent as request parameter. Note that when the value is unspecified, then most browsers default to "on". It's easier if you give all checkboxes the same name but a different and fixed value. This way you can obtain the checked ones as an array/collection.
If all checkboxes are already known beforehand in server side, you can just apply basic math to obtain the unchecked checkboxes:
uncheckedCheckboxes = allCheckboxes - checkedCheckboxes
If those checkboxes are created dynamically at the client side and therefore unknown beforehand in server side, then add for each checkbox a <input type="hidden"> field containing information about the dynamically created checkbox, so that the server side knows which checkboxes are all present as the moment of submission.
Although this goes against the HTML spec, if you know what you are doing, using this you no longer have to cater checkboxes which are handled completely differently when submitted - and for example naming fields with_brackets[] can actually be useable.
Complete solution
$(document).on('submit', 'form', function() {
$(this).find('input[type=checkbox]').each(function() {
var checkbox = $(this);
// add a hidden field with the same name before the checkbox with value = 0
if ( !checkbox.prop('checked') ) {
checkbox.clone()
.prop('type', 'hidden')
.val(0)
.insertBefore(checkbox);
}
});
});
Take note: the non-checked checkboxes now submit a value of "0"
Additionally, if you want to change the behaviour of a single form only, just alter the first line in the above snippet:
$(document).on('submit', 'form.your-class-name', function() {
// ...
});
if you have many checkbox, you can try this code:
<input type="checkbox" onclick="$(this).next().val(this.checked?1:0)"/> <input type="hidden" name="checkbox1[]"/>
If you have the following HTML:
<form id="myform" method="post" action="my/url">
<input type="checkbox" id="checkbox1" name="checkbox1"/>
<input type="checkbox" id="checkbox2" name="checkbox2"/>
<input type="checkbox" id="checkbox3" name="checkbox3"/>
</form>
Normal form submit:
On form submit, before submitting, change all values of checkboxes to 0 and 1 based on if checkbox is unchecked or checked. Like so:
$('#myform').submit(function() {
var $checkboxes = $('#myform').find('input[type="checkbox"]');// Select all checkboxes
$checkboxes.filter(':checked').val(1);// Set value to 1 for checked checkboxes
$checkboxes.not(':checked').val(0);// Set value to 0 for unchecked checkboxes
$checkboxes.prop('checked', true);// Change all checkboxes to "checked" so all of them are submitted to server
});
Note: Ugly thing about this code, while form is submitting, all checkboxes will appear as "checked" for a moment. But if you apply same concept for ajax form submit, it would be better.
AJAX form submit:
$.post('my/url', {
'checkbox1': $('#checkbox1').is(':checked') ? 1 : 0,
'checkbox2': $('#checkbox2').is(':checked') ? 1 : 0,
'checkbox3': $('#checkbox3').is(':checked') ? 1 : 0
}, function(response) {
// Server JSON response..
}, 'json');

How does `event.currentTarget.INPUT.value` give me an input value in a Meteor form submit handler?

I found example code to fetch values of text inputs from a submitted form in Meteor. I wrote my own version. Works great! Here's a snippet from my form submit event handler:
'submit form': function(event, template) {
event.preventDefault();
Assets.insert({
name: event.target.inputName.value,
location: event.target.inputLocation.value,
value: event.target.inputValue.value
});
}
I'm confused about event.target.playerName. What kind of object is it? Does Meteor set up that object for us? Or is this a jQuery thing? Or something else?
Is it any better/safer to use event.currentTarget? Sounds like nesting forms is not allowed, so it might not make any difference since there wouldn't be any way for it to "bubble up" given the 'submit form' event map key.
Crossposted here.
In that case, you're not using the template object but rather the plain jQ way. From a quick look at the page containing the example code, they use function(event) as opposed to function(event, template) (I prefer the latter, but that's a matter of taste). Here's how t make use of the template object.
Suppose your form look like this
<template name='createAccount'>
<form role="form">
<input placeholder="Your Name" name="name" type="text" />
<input placeholder="E-Mail Address" name="email" type="email" />
<input placeholder="Password" name="password" type="password" />
<div id="submitForm" class="outerButton">
(SOME BUTTON)
</div>
</form>
</template>
Here's pattern using template:
Template.createAccount.events({
'click #submitForm': function (event, template) {
var displayName = template.find("input[name=name]").value;
var eMailAddress = template.find("input[name=email]").value;
var password = template.find("input[name=password]").value;
< INSERT displayName, eMailAddress, password IN COLLECTION>
}
})
Pretty new to meteor myself so I could be completely wrong, but I believe your event target is just standard javascript, not meteor or jquery specific. I've been thinking of it as a shorthand for creating your own object.addEventListener(), so your playerName is going to be a child element of the form since it's the key of the object.
Imagine if it was setup something like form.addEventListnener('submit', function(e){ ... }) maybe makes it more familiar.
As for number 2, I wouldn't see why you couldn't use currentTarget if you needed to. I don't think it'd be any safer unless you really didn't know where the event might be coming from (perhaps creating a custom package?).
event.target returns the DOM element. In your case, it's the form element, and you can use named property to get its node, see the spec
In this case it's OK to use either target or currentTarget. In other examples when there is a 'nested' node, it might be better to use currentTarget.

ASP.NET Disable button and run the function

I am facing this issue where I manage to disable button but somehow the function didn't run. I suspect that the function stops right after my button is disabled. Any idea that can solve this issue when user click on the button, the button will be disable immediately and the button will runs the function behind. Below are the codes that I'm using for my button.
<INPUT TYPE ="Submit" NAME ="Submit1" ID = "Submit1" VALUE ="Create New Sales Contract"
SIZE ="30" onclick="**this.disabled=true;*** CheckGWidth(this.form),
this.form.ContractType.value='N'*" >
Note:
this.disabled=true; To disable this button
CheckGWidth(this.form),this.form.ContractType.value='N'
This is a function that will process this page'
Disabling a button won't stop the rest of the code from firing. I suspect there is something else going on.
This works using document.getElementById instead of this.form:
<form id="form1" action="" method="post">
<INPUT TYPE ="submit" NAME ="Submit1" ID = "Submit1" VALUE ="Create New Sales Contract" SIZE ="30" onclick="this.disabled=true;CheckGWidth(this.form);document.getElementById('ContractType').value='N';return false;" />
<INPUT TYPE="text" NAME="ContractType" ID="ContractType" />
</form>
<script>
function CheckGWidth(f){
alert("This works");
}
</script>
JS Fiddle Demo
Use Firebug or Chrome or Developer Tools and check your javascript issues...

Disable Google Toolbar Autofill

The Google Toolbar's autofill feature has been the bane of my web development existance for the past several years. I have always settled on trying to create a timer control to check for changes since the developers epically failed to fire change events on controls. This has gotten further and further complicated when controls are buried inside nested repeaters, and then trying to tie it to an UpdatePanel is a further complication.
Has anyone succesfully been able to prevent Google Toolbar from filling in form fields without renaming the field to something insignifcant? (note: This doesn't work for a 'State' dropdown, it even goes as far as to check field values).
For as smart as Google employees are supposed to be, this was a grandly moronic oversight.
Update: For those who may be coming here looking for a solution. What I have found to work so far is you have ASP.net, is to use the server control "Timer" and to set this control as a trigger for the UpdatePanel. It helps to loop through and check for changed values.
If you only have access to javascript, or are using another framework, then I found using the following function to work the best (I was trying to monitor state and zip changes. The focusElement is required because when hovering in a dropdownlist, it changes the selectedindex):
function MonitorChanges(sStateDropdownID, sZipCodeID, sHiddenStateFieldId, sHiddenZipFieldId, bDoPostback) {
var state = $('#' + sStateDropdownID).val();
var zip = $('#' + sZipCodeID).val();
var hiddenstate = $('#' + sHiddenStateFieldId).val();
var hiddenzip = $('#' + sHiddenZipFieldId).val();
$('#' + sHiddenStateFieldId).val(state);
$('#' + sHiddenZipFieldId).val(zip);
var compareString = state + zip;
var compareHiddenString = hiddenstate + hiddenzip;
var focusElement = getElementWithFocus();
if (compareString != compareHiddenString && isShippingZip(zip)) {
bDoPostback = true
}
if (parseInt(focusElement.id.search('drpState')) == -1 && parseInt(focusElement.id.search('txtZip')) == -1 && bDoPostback) { bDoPostback = false; __doPostBack(sStateDropdownID, ''); }
var f = function() { MonitorChanges(sStateDropdownID, sZipCodeID, sHiddenStateFieldId, sHiddenZipFieldId, bDoPostback); }
setTimeout(f, 1000);
}
According to a recent post by a Google developer, using the autocomplete="off" attribute will disable Google toolbar auto-completion in both IE and Firefox. Note that this attribute must be applied to the <form> tag and not the individual <input> tags:
<form method="post" action="http://example.com" autocomplete="off">
<!-- ... -->
</form>
While this is not an instant fix, it is probably the most reliable solution possible - if it is possible to wait until the next iteration of the Google toolbar.
I once have a problem with autofill in firefox. I did this to prevent it.
<div style="display:none">
<input type="text" name="user" />
<input type="password" name="password" />
</div>
<input type="text" name="user" />
<input type="password" name="password" />
Don't know if it also work with google autofill.
Just out of curiosity, does autofill still fire when you set the AutoCompleteType to disabled?
<asp:TextBox ID="textBox1" runat="server" AutoCompleteType="Disabled" />
I'm not entirely sure if this will work or not, but I recall coming across it as a possible solution.
Try breaking apart the labels of keywords with span tags.
<label for="firstName">Fi<span>rs</span>t N<span>am</span>e:</label>
<input id="firstName" name="firstName">
Also, supposedly Google is planning to support autocomplete="false" in Firefox. No clean IE solution, yet, though.

Passing hidden field from one page to another in querystring

I want to pass a query in a hidden filed from 1 page to another by querystring.
Can anyone help me out with the logic?
It's worth taking the time to learn jQuery. It's not very complicated, and it makes writing javascript much easier. There are also many jQuery plugins, such as jquery.url.
Also, as other posters have suggested, you may not wish to put the hidden field's value in the query string if you care about it being displayed to the user. However, if the data is present in a hidden field it will always be possible for a user to find it if they care to look.
If you really do want to put the hidden field in the query string and then extract it via non-jQuery javascript:
hiddenFieldPage.aspx
This form will take the user to processingPage.aspx?datum=someValue when it is submitted. You could probably also just use an ordinary link if nothing else needs to be submitted at the same time.
<form method="GET" action="processingPage.aspx">
<input type="hidden" name="datum" value="someValue">
<input type="submit">
</form>
or, inserting the value from code-behind:
RegisterHiddenField("datum", "someValue");
processingPage.aspx
This script will pop-up an alert box with the value of "datum" from the URL - assuming the form's method is set to "GET":
<script type="text/javascript">
function getUrlParam( key ) {
// Get the query and split it into its constituent params
var query = window.location.search.substring(1);
var params = query.split('&');
// Loop through the params till we find the one we want
for( var i in params ) {
var keyValue = params[i].split('=');
if( key == keyValue[0] ) {
return keyValue[1];
}
}
// Didn't find it, so return null
return null;
}
alert( getUrlParam("datum") );
</script>
If the form's method was set to "POST" (as it usually would be in ASP.NET), then "datum" won't be in the query string and you'll have to place it on the page again:
RegisterHiddenField( "datum", Request.Form["datum"] );
To retrieve the hidden value on the second page:
var datum = document.Form1.item("datum").value;
alert( datum );
You can easily submit a form on one page that points to another page using the action parameter. For instance, inside of page1.aspx put the following:
<form action="page2.aspx" method="GET">
<input type="hidden" name="username" value="joenobody" />
<input type="submit" />
</form>
Since you're using "GET" as the method instead of "POST", you could potentially use Javascript to parse the URL and get the value that was passed. Alternatively, you could use ASPX to store the value of the "username" field somewhere else on the page. I don't know ASPX (or ASP, or anything Microsoft really), but if you can find a way to output something like the following (and are using jQuery), it may do what you require. Honestly though, it sounds like you are going about something all wrong. Can you modify your question to be a bit more specific about what the general object is that you are attempting to accomplish?
<div id="some_div"><%= Request.form("username") %></div>
<script type='text/javascript'>
var value_needed = $('#some_div').html();
</script>
<form method="get">
Assuming you mean hidden in the HTML form sense, your field will be submitted along with all the other fields when the form is submitted. If you are submitting via GET, then your "hidden" field will show up in plain text in the URL. If you don't want the data in the hidden field to be accessible to users, don't put an understandable value in that field.
If you are using aspx, you do not need to parse the query string using JavaScript, or even use <form method="GET" ...>. You can POST the form to the second aspx page, extract the value in C# or VB then write it to a client-side JavaScript variable. Something like this:
page1.aspx:
<form method="POST" action="page2.aspx">
<input type="hidden" name="myHiddenServerField" value="myHiddenServerValue">
<input type="submit">
</form>
page2.aspx:
<script type="text/javascript">
var myHiddenClientValue = '<%= Request.Form['myHiddenServerField']; %>';
</script>
The above would set the client-side JavaScript variable called myHiddenClientValue to a value of 'myHiddenServerValue' after the POST.
This can be a bad idea because if myHiddenServerField contains single quotes or a newline character, then setting it on the client in page2.aspx can fail. Embedding ASP.NET Server Variables in Client JavaScript and Embedding ASP.NET Server Variables in Client JavaScript, Part 2 deals with specifically these issues, and solves them with a server-side class that ensures values being written to the client are escaped correctly.
If you use method="get" on an HTML form then any hidden inputs in that form will be converted to query parameters.
See also Jeremy Stein's answer.

Resources