How do I (easily) dynamically name helper elements in Razor? - razor

I'm just starting out in Razor, and my first inclination was to treat Helpers like .ACSX's.
Let's say I make a very simple helper:
#helper HowManySpans() {
<div>
<input type="text" name="txtLoops" /><input type="submit" value="how many?" />
#{ if (IsPost) {
var count = Request["txtLoops"];
var i = 1;
while (i < count) {
<span>Span ##i</span>
i++;
}
}
</div>
}
It works fine until I place two on the same page. I was expecting the compiler to emit the name of the elements prefixed like ASPX pages generally do, yknow, ctl00_Header_txtLoops or something like that.
I guess in a more argument-driven helper, I could use my arguments to prefix names myself, but I feel that still postpones the issue. If I had some dynamic helper that prefixed names with a certain argument, I could still only have one on a page with that argument.
Am I overlooking something painfully obvious?

Razor emits only the markup that is in the page. It has very little in the way of augmenting the markup. Razor v2 added conditional attributes, but that is still somewhat explicit on behalf of the developer.
One question I have is why do the elements even need unique names. In many modern HTML5 applications there is little need for elements to have unique names.
But, suppose, there is a need, there are two ways I can think of to do it:
Have the caller pass in a name or name prefix (as you suggested).
Create your own counter, and increment it every time the helper is called. The big question is where to save the counter's information. One logical place to save it would be the HttpContext.Items collection, which is a per-request "bag of data". Each time the helper is called it checks the Items bag to see what the current count is, increments it by 1, uses that number, and updates the bag.

Related

HTML single Checkbox: Best practise whether to use value attribute or not

today i had a discussion with my colleague. The question was whether to use the additonal value attribute for a single HTML checkbox or not.
My preffered way is using a single checkbox without a additional value attribute and in backend doing a check like if
if (request.getParameter(checkboxName) != null)) {
...
}
My colleague argues that is would be more transparent using a single checkbox with a additonal checkbox value attribute like value="true" and doing a backend check like
if (Boolean.valueOf(request.getParameter(checkboxName))) {
...
}
As we want to make a small convention about our internal checkbox handling im now trying to find a "best practise" but couldn't find yet. I saw so far only examples with multiple checkbox with the same name. In this case of course it makes sense for me to use different values.
For me it seems to be a bit overhead using a value attribute in case of a single checkbox since i get always a String with "on" if its activated/checked.
We are using a Java Servlet/JSP MVC environment and im not 100% sure if this "on" comes from ServletRequest.getParameter.
I see reasons for following either method, which means there's probably no noticable difference between them. Whichever you pick will work out fine; just make sure you pick one. You could flip a coin or do a thumbwar or something.
As long as a single approach is consistently used, both will work. Yours is less code and doesn't require boolean conversion, the other´s html is more consistent with multiple checkboxes but will also break if you put the wrong value for whatever reason.
You could always do a bit of both and insert values in html for clarity but check for != null in the code and get the best of both options.
It makes no difference server-side as long as you are not checking the parameter for having a specific value. By HTML5 definition, which just establishes the longstanding practice as the rule, a checkbox element has the value on by default. This means that your server-side code cannot distinguish between data coming from <input type=checkbox name=foo> and data coming from <input type=checkbox name=foo value=on>.

What to render to html form If I need to send multiple (hidden) values with the same key?

Let's say I have got a form with only one visible input (a checkbox for instance) and I need to send the value of that input along with an array of ids that identifies objects that should be modified based on the value of that visible field, i.e. POST data should look something like this:
active=1
ids=1
ids=2
ids=3
...
ids=1000
I know that I can render 1000 hidden inputs for each id in ids array. But isn't there a better way (that avoids generating so much markup)?
Name each of your hidden inputs like this
<input type="hidden" name="array_input[]" value="1" />
Then on the php side use $_POST['array_input'] as ordinary array
print_r($_POST['array_input']);
Well, that's not how many inputs with the same name are sent. In reality, you're going to get something more like this:
ids=1,2,3,4
It should be pretty easy to build this value in Javascript. In fact, why do you care how the POST data is sent? Just build a string of values, send it and parse it on the server :)
Or are you using some kind of server that expects to get 100 POST values with the same key? I thought the contract was that the key should be unique? Checkboxes work that way in plain HTML...

AS3 Advanced Variable Usage - Retrieve Value In Variable Selected Based On Value In Another Variable

I am working on creating a project which allows me to define objects in an XML document and have flash create the required items and display at run time. Needless to say, it is slow progress making this up and learning as I go along.
I have now reached a hurdle, which by comparison should be really easy. But I'm drawing a blank. Despite spending several hours with my good friend Google, I don't seem to be able to phrase this in such as way as to find other people who want to achieve the same.
Description
Currently I have a menu handling class, which is where the issue lays. An instance of the menuHandler class is created. It is used by calling a class (LoadFramework) which is passed two strings. One is the address of an XML file, the other is a tag within that XML document to specify what part of it needs to be read.
The XML document is loaded by a class and then parsed into a variable. Then depending on the second string passed (the value of the XML tag), the appropriate part of that XML document is translated onto the screen. This all works fine, but here is the catch...
The only way I have managed to get this working is to use a switch statement with a case for every potential tag. Then I write an appropriate for-each-in loop. The following is an example of one of the case statements (they are all identical except for the "event.dat.XYZ.element" part). "event.dat" is a variable passed by a custom handler, it contains the XML data. XYZ is the name of the tag (in this case "home") and each "element" is a tag containing an attribute.
case "home":
for each (var menuField:XML in event.datPass.home.element) {
mnDataHold.push(menuFieldHome);
loopCount ++;
} // for each (var menuField:XML in event.datPass.home)
ActionMenu(loopCount);
break;
An example of the XML that is held in event.datPass.
<home label="home">
<element label="menuType">HomeScreen</element>
<element label="screenType">Game.assets.menuScreens.homeScreen</element>
<element label="buttonCoords">400,50,400,100,400,150,400,200</element>
<element label="buttonNames">baseButton,baseButton,baseButton,baseButton</element>
<element label="labelCoords">440,51,425,101,430,151,438,201</element>
<element label="labelTexts">Play,Options,Credits,More</element>
<element label="labelColors">0xFFFFFF,0xFFFFFF,0xFFFFFF,0xFFFFFF</element>
<element label="labelSizes">22,22,22,22</element>
<element label="labelBolds">true,true,true,true</element>
<element label="buttonCommands">startGame,diplaysMnuOptions,displayMnuCredits,displayMnuMoreGames</element>
</home>
The Request
What I want to do is replace part or all of the object in the for-each-in loop with a variable, and then evaluate the string as a reference rather than using it as the value.
So that I can end up ditching the switch and simply have something like:
for each (var menuField:XML in [mnVariable]) {
mnVariable would contain the string, eg "event.datPass.home.element".
Or:
for each (var menuField:XML in event.dat.[mnVariable].element) {
mnVariable would contain the string, eg "home".
However, written the first way, all that happens is that the for-each-in loop looks in mnVariable to find the value in menuField, which it won't find. Written the second way it will just throw an error. I need [mnVariable] to be used to evaluate as meaning 'look in the object named by this string'
Any pointers are very gladly received.
Generally not a fan of having data-defining element names in XML, but - assuming event.dat is actually an XML object, and not an arbitrary object that you've manually parsed the XML into (can't tell from the question) - this is really a question about ECMAScript for XML (E4X) rather than variables in general.
If so, this should work:
for each (var menuField:XML in event.dat.child(mnVariable).element)
{
// Do something
}
Can't test at the moment, but this may also work (it's part of E4X standard, but not sure if Adobe implemented it):
// Note, no dot before the indexer:
for each (var menuField:XML in event.dat[mnVariable].element)
{
// Do something
}
The latter is also generally the way to access a property of an object using a string property name, so if event.dat is an arbitrary object of manually parsed XML - as opposed to an actual XML object - the second example should also work.

Should I use one form on page or generate a form per item?

I want to display a list of items. Each item would have an edit and a delete icon next to it.
For obvious reasons I want to trigger the delete action with HTTP POST.
With jQuery, I would bind links to trigger form.submit.
However I'm not sure if I should generate a form next to each item or use just one form.
Below are pros and cons of two approaches as I see them.
Form Per Item:
easy to generate;
no need to fiddle in JS to set action and input value.
Single Form:
makes more sense semantically;
requires client JS to set hidden input;
requires client JS to set form action (e.g. id + '/delete/).
What is there to add? What is the preferred pattern in modern HTML apps?
I have used checkboxes in the past. This is better for usability, and each checked checkbox can pass its own ID to the form processing script.
The main disadvantage I see in having a single form enclosing all list elements is that you can end up with a huge POST if the list is long. As an advantage, you could mark multiple elements for deletion (checkboxes, for instance) and perform a single delete request.
I'd go for either
A single form for each list element. This would make deletion of multiple elements impossible, but would keep POST sizes minimal.
Using a single form, but in a way that doesn't include all the list elements. For instance, having a delete only form with a single hidden element in it, into which you would put all the id's marked for deletion with JS manipulation.
As a side note, you could also skip forms and perform the needed interactions through ajax. This would improve user experience notably. Take into account that forms would still be needed to provide fallback mechanisms in case it was required.
In the end, I decided to go with AJAX via jQuery.ajax.
The reason is semantically I don't even have forms—I have buttons.
Therefore, jQuery is an easier solution as it allows to keep posting logic in one place (as opposed to scattering it across HTML and JS).
I assigned row class to each semantical row and put corresponding database IDs in HTML5 data attribute called data-row-id for each row.
<div class="row" data-item-id="{{ product.id }}">
<!-- ... --->
<img src="/img/delete.png" alt="Delete">
</div>
Then I have something alone the lines of
$('.delete-btn').click(function() {
var row = $(this).closest('.row');
var id = row.data('item-id');
$.ajax({
url: id + '/delete/',
type: 'POST'
});
row.fadeOut().slideUp();
return false;
}
in my $() load handler.
This solution scales beautifully across the whole codebase because you only have to set row class and data-item-id attribute and the buttons will “just work”.

Compound object in HTML <button> value attribute

If for some reason it were mandatory to associate a <button> with more than one value, is there a good way to do it? For example ...
CSV:
<button value="Lancelot,Grail,blue">Answer</button>
JSON:
<button value="{'name':'Lancelot','quest':'Grail','color':'blue'}">Answer</button>
In the absence of a good way to do it, is there a traditional way?
Edit: another use case
Server M, the producer of the HTML, knows the user's current location and favorite genres, movie names, nearest theater, and next showtime. Server F knows how to query various 3rd party servers about how to get from point A to point B in order to arrive by time T. The user knows only the movie names: click Drag Me to Hell, and get the route. Server M could generate a form for each movie, with a single button showing the name of the movie and multiple hidden fields with the start and end locations and desired arrive-by time, but that would require a lot of repeated code. Every one of these one-button mini-forms would have the same method and action and the same hidden input field structure. Styling would be a collection of mini-forms rather than a collection of buttons, so FIELDSET and LEGEND are unavailable (because HTML forbids nested forms). Putting the parameters into the button's value attribute would be much tidier.
Well if you have to have a button element, why not use JavaScript to set a bogus property:
$('mybutton').compoundValue = { ... json ... };
and then reading the 'compoundValue's during form submit, etc.
Though really you might want to consider a group of checkboxes or some other form bits for what you're trying to accomplish.