Passing hidden field from one page to another in querystring - query-string

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.

Related

Controller does not receive value from view (implementing search function) on MVC

I'm trying to make a page with a search function. When you first go to the page, all you have is a search bar. When you type something into the search bar and click the "submit" or "search" button, I want the value in the search box to be submitted to the controller as a string. Then, this value can be used in returning the a model back to the page. Here's what I have so far:
Search.cshtml
#{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#ViewBag.PageTitle
<h1>Search All Issues</h1>
<form asp-controller="Report" asp-action="Search" method="get">
<input name="searchstr" id="Search" />
<input type="submit" value="Submit" />
</form>
ReportController.cs
[HttpGet]
public ActionResult Search(string test)
{
ViewBag.PageTitle = test;
var report = _context.Reports.ToList();
return View(report);
}
What am I doing wrong here? For now, it would be nice if I can just get that ViewBag.PageTitle to appear on the page. If I can do that, then I can return the report model just the way I want.
Also, a few additional questions. Some of the stuff I've seen on stack overflow has a recommendation to do a Post in the controller. If I do that, the page errors out. Why is a get needed for this? Intuitively, it makes more sense to me to use a Post...
Turns out I was extremely close; Stephen Muecke had the correct answer. I simply needed to change my input name or parameter name.
I made this mistake as I was considering this from a C++/C standpoint where the parameter names can be irrelevant. I see now, though, that with ASP.NET MVC, you need to have the input name match the parameter name.
Thanks for the help!

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 MVC3: Razor GetHTML Table custom layout

Im manually Creating the table using the built in razor GETHtml Function.
#table.GetHtml(
columns: table.Columns(
table.Column("Account"),
table.Column("Due"),
table.Column("Topic"),
table.Column("Type"),
table.Column("Completed?", format: #<input id="Complete" name="Complete" type="checkbox" onclick="/Tasks/Complete?ID=700" />)
)
)
What I want is a way of clicking a checkbox, or button to activate the controller. it is not accepting Dynamic checkbox. Nor does the html checkbox do anything.
I Have a working solution without using forms, the column would be set using the following code:
table.Column("Completed?", format: #<input type="checkbox" onclick="location.href='#Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })'" />
I think its possible that having the name property was causing it to post it as a parameter, rather than treat it as a submit.
Otherwise it must ahve been the onclick event. Ive used location.href, then set it using razor syntax, and included the id as a property.
Couple of ways to go about performing a post to your desired controller. Wrap your table with the form you would like to submit or add a few AJAX handlers to post the data you desire. A simple form could be accomplished like:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction())
{
#table.GetHtml(
columns: table.Columns(
table.Column("Account"),
table.Column("Due"),
table.Column("Topic"),
table.Column("Type"),
table.Column("Completed?", format: #<input id="Complete" name="Complete" type="submit" " />)
)
)
}

Orchard and master detail editing

I was reading http://www.orchardproject.net/docs/Creating-1-n-and-n-n-relations.ashx and could not get the idea, if it is possible to easily make master detail editing, to give you concrete example i've attached screenshot from wordpress:
So there is post and post contains set of custom fields, simple 1:N relationship, everything edited in one page - you can add/edit custom field without leaving post page.
May be someone saw similar example for Orchard on internet, or could shortly describe path to achieve this by code, would be really helpful (I hope not only for me, because this is quite common case I think).
This should be possible, although not in the most 'Orchardy' way.
I've not tested any of the below so it is probably full of mistakes - but maybe Bertrand or Pszmyd will be along later today to correct me :-)
As you have probably seen you can pass a view model to a view when creating a content shape in your editor driver:
protected override DriverResult Editor(CatPart part, dynamic shapeHelper)
{
// Driver for our cat editor
var viewModel = new CatViewModel
{
Cats = _catService.GetCats() // Cats is IEnumerable<Cat>
};
return ContentShape("Parts_CatPart_Edit",
() => shapeHelper.EditorTemplate(
TemplateName: "Parts/CatPart",
Model: viewModel,
Prefix: Prefix
));
}
So we can pass in a list of items, and render it in our view like so:
#foreach(var cat in Model.Cats)
{
<span class="cat">
<p>#cat.Name</p>
<a href="...">Delete Cat</p>
</span>
}
The problem here would be posting back changes to update the model. Orchard provides an override of the Editor method to handle the postback when a part is edited, and we can revive the viewmodel we passed in the previous method:
protected override DriverResult Editor(CatPart part, IUpdateModel updater, dynamic shapeHelper)
{
var viewModel = new CatViewModel();
if (updater.TryUpdateModel(viewModel, Prefix, null, null))
{
// Access stuff altered in the Cat view model, we can then update the CatPart with this info if needed.
}
}
This works really well for basic information like strings or integers. But I've never been able to get it working with (and not been sure if it is possible to do this with) dynamic lists which are edited on the client side.
One way around this would be to set up the buttons for the items on the N-end of the 1:N relationship such that they post back to an MVC controller. This controller can then update the model and redirect the client back to the editor they came from, showing the updated version of the record. This would require you to consistently set the HTML ID/Name property of elements you add on the client side so that they can be read when the POST request is made to your controller, or create seperate nested forms that submit directly to the contoller.
So your view might become:
#foreach(var cat in Model.Cats)
{
<form action="/My.Module/MyController/MyAction" method="POST">
<input type="hidden" name="cat-id" value="#cat.Id" />
<span class="cat">
<p>#cat.Name</p>
<input type="submit" name="delete" value="Delete Cat" />
</span>
</form>
}
<form action="/My.Module/MyController/AddItem" method="POST">
<input type="hidden" name="part-id" value="<relevant identifier>" />
<input type="submit" name="add" value="Add Cat" />
</form>
Another possibility would be to create a controller that can return the relevant data as XML/JSON and implement this all on the client side with Javascript.
You may need to do some hacking to get this to work on the editor for new records (think creating a content item vs. creating one) as the content item (and all it's parts) don't exist yet.
I hope this all makes sense, let me know if you have any questions :-)

Resources