MVC 3 Passing Variables Between Actions - html

I'm working on a website where I need to pass variables between actions. The variables are actually input fields. Here is some example markup.
<table>
<tr>
<td><input type="checkbox" name="major/1" value="1" checked /></td>
</tr>
<tr>
<td><input type="radio" name="major/2" value="1" checked /></td>
<td><input type="radio" name="major/2" value="2" /></td>
</tr>
</table>
Next Page
I basically want the values of those passed through a pagination system so it can be all used by the end. How could I accomplish this? Preferably without the use of a form surrounding the entire page.

The only way to pass input form elements from one page to another is through a form post. You can certainly pass data via session or similar, but that's not passing them in form elements.
I don't understand you reluctance to use a form. hidden fields are form elements. They're used in forms. That's their purpose. You want to use form elements but not use a form? That's pretty pointless.
EDIT:
I think your problem is that you don't truly understand the way a browser and server work. They only communicate via get and post commands. Therefore, the only way to send an input to the server is via a post, and a post must contain a form. That's how a browser sends it's data.
There's a lot of things you could do via javascript, but all of those things would be a lot messier than just doing your post.

I could see two possible methods. First, use hidden input fields inside the postback form. This will ensure variables from the current iteration get saved to the model on postback:
#Html.HiddenFor(model=>model.Field1)
The second would be to save whatever you need to TempData on the controller side and retrieve it on the next postback:
TempData["tempkey"] = MyModel;
I think that whether the best solution is one of these (or something else) depends on what your model and controller logic looks like.

The easiest way to accomplish this without using a form would be to use jQuery or javascript to grab the values and append them as url variables, assuming that is an acceptable approach. The other way would be to capture the values, send them ahead of time via ajax, and have your backend store them as session variables prior to following the link First, give the link a class name to listen to...
$('.navigation').on('click', '.pagelink', function(e){
e.preventDefault();
// url variables method
var theUrl = ($(this).attr('href')) + '?';
var ajaxUrl = $(this).attr('href');
// needed for ajax method
var theVals = new Object();
$.each('table input', function() {
// needed for ajax method
var theName = $(this).attr('name');
theVals[theName] = $(this).val();
// url variables method
theUrl = theUrl + theName + '=' + $(this).val() + '&';
});
// url variables method
theUrl = theUrl.substr(0, theUrl.length - 2);// removes ending ampersand
window.location = theUrl;
// the ajax session method
$.ajax({
url : [MVC path to store session variables - ex: /ajax/setsession/],
type : 'POST',
data : theVals,
success : function(data) {
if(data) {
// do something with data, like display success message
window.location = ajaxUrl;
}
}
});

Related

enter term into hidden form field with html and css possible?

I have created a form in HTML/CSS on my website.
Now, my idea is to give out links that would contain some string (basically like an affiliate link) and would like that string to be entered in a hidden form field to be submitted, or somehow else, have that string in the submitted data.
is there an easy way to do this?
There are two ways of approaching this, both of which use a GET variable in the link you distribute.
First off, let's assume that--for example's purpose--your special string is abc123. You would then distribute a link that follows the form http://example.com/my/form/?affiliate=abc123.
Assuming that, here are two solutions, one in PHP and another in Javascript.
PHP Solution
This one is fairly easy, as long as you're just setting a hidden field.
<input type='hidden' name='affiliate' value='<?= htmlspecialchars($_GET['affiliate'], ENT_QUOTES, 'UTF-8'); ?>' />
Update: Added htmlspecialchars() call to escape any input, to prevent security issues with users setting the GET variable manually.
Javascript Solution
HTML
<input type='hidden' id='affiliate-input' name='affiliate' />
Javascript
This solution relies on jQuery. If you want a pure JS solution, let me know.
var $_GET = {};
// When the page loads, set the input value
$(document).ready(function(){
setupGetVariables();
var affiliateId = $_GET["affiliate"];
$("#affiliate-input").val(affiliateId);
});
function setupGetVariables()
{
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location
.toString()
// get the query string
.replace(/^.*?\?/, '')
// and remove any existing hash string (thanks, #vrijdenker)
.replace(/#.*$/, '')
.split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
}
The setupGetVariables() method was helped by this answer.

Get all the form input fields from a Page

So basically, I have a lot of form fields (About 50 or so). Doing an AJAX request is going to be astronomically big, and it will most likely just make my code look ugly and unreadable. Is there anyway to gather all form data from a page and do an AJAX request?
If you had the names of the object for each input box like:
<input type="text" data-ajax="MyAjaxObjectName1" />
You could recurse through all of the inputs in this way:
var ajaxObject = {};
$('#myContainer input[type=text]').each(function() {
var inputObject = $(this).data('MyAjaxObjectName1')
ajaxObject[inputObject] = $(this).val()
}
That is the simplest way I can think of to recurse through every field that you have. Although, you'd have to update the HTML to include those attributes
The jQuery 'serialize' method:
Description: Encode a set of form elements as a string for submission.
See https://api.jquery.com/serialize/
I suggest to use $.serializeArray() on the form element.
It returns an array with each name and value of form inputs.
Docu & examples: https://api.jquery.com/serializeArray/

Redirect to URL using code in GET form

I am working on a project in Squarespace to create a very basic combination lock form where inputting different codes (invoice #'s) takes you to specific URLs. Because it is Squarespace, I don't think I have very many options for coding other than html (but I could be wrong - I'm very much in learning-mode!!).. I did find a similar question here Query String Redirection: How to change form input to URL?, but how to implement the response into squarespace's code block is way beyond me...
Right now my code looks like this:
</span></p>
<div style="margin-top:5px;">
<form method="GET" action="/our-team/bob">
<div class="input-append">
<input class="span2" id="appendedInputButton" name="code" type="text">
<button class="btn btn-primary" type="submit">Submit!</button>
</div>
</form>
</div>
Using this code, the form takes you to the our-team/bob page every time, regardless of what is entered into the form. e.g. if 0000 is entered into the form, I am redirected to www.mydomain.com/our-team/bob?code=0000 -- which is still just the our-team/bob page; if 1234 is entered into the form, I am redirected to www.mydomain.com/our-team/bob?code=1234 --- which is still just the our-team/bob page; and if nothing is entered into the form and I click submit, it still redirects me to the our-team/bob page.
Ideally, each unique code will bring me to a unique page that I have developed. But squarespace doesn't let me use a "?" in a page url, so I can't just redirect that way. I would like to be able to enter a specific code that takes me to a corresponding page and need to check the code against an array with some simple logic like this:
If string is 1234, go to /our-team/bob
If string is 5555, go to /our-team/jane
If string is 0000, go to /our-team/allen
(etc.)
If string is anything else, show an error and not leave the page at all OR go to some sort of error page.
Hopefully this makes sense (and hopefully it is possible to do!) Please let me know if there is any other information I can provide you with. Your help is VERY much appreciated!
What you are asking for is not possible with HTML and standard HTTP protocol. The form values are either sent as query string parameters (if you are using GET) or as part of the request body (if you are using POST). Here you seem to be asking to make some mapping between the value entered by the user and the specific page being called on the server. The only way to achieve that is to use some javascript. Subscribe to the onsubmit event of the form and write the mapping between the client value and the server one:
<form method="GET" action="/our-team/bob" onsubmit="return handleSubmit();">
...
</form>
and then you could define the handleSubmit function to implement your custom logic:
<script>
var handleSubmit = function() {
var value = document.getElementById('appendedInputButton').value;
if (value === '1234') {
window.location.href = '/bob';
} else if (value === '5555') {
window.location.href = '/jane';
} else if (value === '0000') {
window.location.href = '/allen';
} else {
window.location.href = '/some-default-page';
}
return false;
};
</script>

HTML Form - submit array of ID's of selected divs

I have an array of divs which can be selected (change background colour on click to signify that to the user).
I want a way to submit the ids of all of these divs to my app, though can't see a 'nice' way of doing this; at the moment the only thing I can see to do is have a button that onclick triggers a javascript function that gets the id's and sends them back to my server in a POST.
Is there a way of creating a multiple select input on a form which uses divs instead of checkboxes or a multi-select list, or a better way of doing what I'm attempting?
Assuming you add the class selected when a user 'selects' the div:
var data = {};
$(".classOfDivs.selected").each(function(){
data[$(this).prop('id')] = 'true';
}
$.ajax({
url : 'ajaxPage.php',
type : 'POST',
dataType : 'text',
cache: false,
data: data,
success : function(text){alert('Saved: '+text);},
error: function(){alert('Did not reach server');}
});
Use the success function to process the returned text as needed. dataType can be changed to html, JSON, etc. See the .ajax() documentation.
Have a hidden input for each div, all with the same name but with a different id. When a div is clicked update the corresponding hidden input with the id. Then when you submit through a standard form POST all of those values will be available through the name you specified.
Since this is an app, what you could do is store everything in HTML5 localstorage using the JQuery javascript library.
Here's how to do it step by step:
Create a jquery array
on click, get div id and store it in the array with a key/value pair
if clicked again, remove it from the array
have some event listener like a "submit" button to store the value of your array to localstorage
Here is a jsfiddle I had that has exactly what you are talking about: http://jsfiddle.net/CR47/bqfXN/1/
It goes into a little more depth but the jquery should be exactly what you need.
The reason this is better than submitting with POST or using ajax is because since you say this is an app, you will be able to use this method offline, where as post or ajax would require a connection to a server running php.
var skinCare=[]; //the array
$('.skinCare').click(function(){ //onclick
var value = event.target.className.split(" ")[0]; //get classname, you would get id
var index = skinCare.indexOf(value); //gets where the location in
//the array this code is
if($(this).hasClass('selected')){ //when a div is clicked it gets
//$('.skinCare').removeClass('selected'); //the class "selected" and adds
skinCare.splice(index, 1); //to array, then another click
} else if($.inArray(value, skinCare) == -1){ //removes it from array
skinCare.push(value);
}
});
$('.submitbutton').click(function(){
localStorage.setItem('Skin Care', JSON.stringify(skinCare));
});

Save input data to localStorage on button click

I am trying to build my first web application. In my app I need to have a settings panel, but I have no idea how to do it. I've been searching the web and came across a HTML5 localStorage, which I believe might be the best way to do the things. But the problem is I have no idea how to use it.
<input type='text' name="server" id="saveServer"/>
How can I save data from input to localStorage when user clicks the button? Something like this?
<input type='text' name="server" id="saveServer"/>
<button onclick="save_data()" type="button">Save/button>
<script>
function saveData(){
localStorage.saveServer
}
</script>
The localStorage object has a setItem method which is used to store an item. It takes 2 arguments:
A key by which you can refer to the item
A value
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.val());
The above code first gets a reference to the input element, and then stores an item ("server") in local storage with the value of the value of that input element.
You can retrieve the value by calling getItem:
var storedValue = localStorage.getItem("server");
This worked for me. For setting I placed .value behind the var and called the var in the setItem:
var input = document.getElementById('saveServer').value;
localStorage.setItem('server', input);
For getting the text back:
document.getElementById('saveServer').value = localStorage.getItem('server');