ASP.Net MVC passing a database string to a CheckBox value - html

This is closely related to a question I posted yesterday regarding CheckBoxes.
Here is my setup:
I have a database directory, with a list of names, among other fields, as my model.
I have a search page where users can search this directory and select a name.
I have a form page that displays the name with a checkbox next to it which allows the user to decide if they want to include the name as a value in the submitted form.
A controller that handles the submitted form.
Goal:
What I would like to know is, how can I get the string value of the name that was selected in the directory to both display in the form page View, and also include this string in the value field of the CheckBox?

You cannot change what the value of a checked check box; check boxes always get posted with "on" as their values if checked, and MVC can use this to automatically map the posted values to booleans. However, if this list of names is dynamic, and each name is unique, you can generate the form with dynamically-named check boxes. Then, in the controller, you can inspect the raw form to see which names were checked. For example, in the view, your code could look something like this:
<form>
<% /* Some loop here */ { %>
<input type="checkbox" name="name_<%= Html.Encode(theName) %>" />
<label><%= Html.Encode(theName) %></label>
<% } %>
</form>
Then, in the controller:
foreach (string name in listOfAvailableNames)
{
if (Request.Form["name_" + name] == "on")
{
// Handle the name being selected
}
else
{
// Handle the name not being selected
}
}

Related

What is the correct and most safe way to check if HTML form checkboxes and such have been POST-set?

This has confused me since the early days. Maybe it's just in my head, but it seems to me as if this has varied over time, between browsers, and possibly even depending on the local language/locale.
Basically, whenever I need to check if a HTML input of type "radio" or "checkbox" has been set, I always do:
if (isset($_POST['the_name']) && trim($_POST['the_name']))
// do stuff
This just makes sure that the POST variable is sent whatsoever (which in itself doesn't mean that it was actually checked/selected, as far as I can tell, since its "value" can be an empty string) and that it's something other than '' (empty string). It seems like this has worked for a long time, but I have two problems with it:
It's ugly. I need to abstract it into a function, but then I want to know if it's a good idea in the first place, or wrong somehow.
It makes the assumption that any non-empty string value means "checked" or "selected", whereas the standard may say a specific string value such as "on", or maybe any number of such strings depending on the language/locale.
Are there cases where my above code falls apart? Do browsers ever submit POST forms where they include names which have no user input/selection in the HTTP request? Or does the existence of a name in the POST blob mean that that "field" has been actively changed/set/checked/selected?
The idea behind checkboxes is that the value is sent over to the server only if the checkbox was checked when submitting the form. The value can be anything, even an empty string. As long as the field is part of the transmitted form it means the box was ticked.
The value attribute is one which all <input>s share; however, it serves a special purpose for inputs of type checkbox: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute. If the value is not otherwise specified, it is the string on by default.
This means you could have a form like this:
<form action="" method="get">
<input type="checkbox" name="c1" value="">
<input type="submit" value="Send">
</form>
If the checkbox is not checked when submitting then $_GET will be an empty array.
If the checkbox is checked then the value of $_GET will be:
array('c1' => '');
To check whether the box was ticked when sending the form you only need isset()
if (isset($_POST['c1']) {
// The box was checked!
}
Sometimes you would like to assign a value attribute to your checkbox. In such situations you can use the shorthand operator for isset() function ??.
// Create a variable from the checkbox value or assign an empty string if the box was not checked
$nyCheckbox = $_POST['c1'] ?? '';

Need Validation on html dropdownlist with data from Viewbag

I know I'm not supposed to use the Viewbag and that I should build a menu using Html.DropDowlListFor() so that i can add attribute bound to the members of the model, BUT, that would involve a pretty extensive code rewrite....
I have a custom controller with a menu:
*.ASCX
<%: Html.DropDownList("CityIDs", new SelectList(ViewBag.cities, "Id", "Name"), "--Select--", new { style = "width:200px" })%>
<%= Html.ValidationMessage("CityIDs") %>
The List populates just fine and I can default to the top item to "--Select--"
The prbolem is that I want the validation error to occur on anything that is not from the viewbag.... how can I achieve this?
Validation for dropdown lists only ensures that something was posted. If you want to ensure that the value that was posted is actually one of a set of "allowed" values, then you'll have to manually do that in your post action:
var cityIds = db.Cities.Select(m => m.Id);
if (!cityIds.Contains(model.CityIDs))
{
ModelState.AddModelError("CityIDs", "You must select one of the available choices.");
}
if (ModelState.IsValid)
{
...
Two things:
Notice that I'm pulling the city ids straight from the database (the actual code you'd need here, of course, depends on your specific implementation). The important thing, though, is that ViewBag only survives a single request, so you can't look for them in ViewBag after posting.
Despite the pluralized name of CityIDs, using the DropDownList helper ensures that only a single selected value will exist. If this is actually supposed to be a multiselect, then you need to use ListBox instead, and update this conditional here to account for check for multiple values.
Populates the top item with Text = "--Select--" and Value = ""
which will post a blank value for CityIDs and cause an error in ModelState.

Razor Form Submission with Extra Information from Model

I am currently attempting to submit a Form while adding extra information from a propagated model. Like my model already has information, and I wish to pass that along with the Form submission.
E.g. TestModel has Name, Date, and ReadTime properties.
In the View:
#using(Html.BeginForm(FormMethod.Post)){
#Html.TextBoxFor( model => model.Name, "Enter Name");
}
Notice how my form only submits the name, but I would like the Date to be submitted as well, which is propagated through from some other view. How would I achieve this?
EDIT: Assume that DATE is passed down into the View when the View inherited the model. Like Date already comes with the Model, and I need to pass it through with the form.
EDIT2: Date comes from the upper View hierarchy which calls this Partial View, which subsequently submits a form. I need the Date, which comes from upper view, to be submitted as a part of the form.
Just use a hidden input for Date like this:
#using(Html.BeginForm()) {
#Html.HiddenFor(model => model.Date)
#Html.TextBoxFor(model => model.Name, "Enter Name");
}

HTML form doesn't contain a form submit button name when using the Enter key

My ASP.NET MVC 3 website has code on the server side that checks for the name of the submit button clicked to submit the form. The code works when I use the mouse to click the button, but when I use the Enter key, the form gets posted, but the request doesn't contain the name of the submit button.
Is there some attribute I can set on the submit button to get this to work for both clicking and using the Enter key?
Here is my HTML:
<div>Search:</div>
<form action="/Item/Search" method="post">
<input class="fulltextsearch" id="FTSearchText" name="FTSearchText" type="text" value="" />
<input type="submit" value="Go" name="FTSearchButton" />
</form>
</div>
On the server side, I have a custom model binder that uses the following code to determine if the user clicked the submit button.
// See if the value provider has the required prefix
var hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : string.Empty;
var searchButton = GetValue(bindingContext, searchPrefix, "FTSearchButton");
// If this value doesn't have value, the user didn't click the button so exit
if (string.IsNullOrEmpty(searchButton)) {
return null;
}
private static string GetValue(ModelBindingContext context, string prefix, string key) {
var result = context.ValueProvider.GetValue(prefix + key);
return result == null ? null : result.AttemptedValue;
}
Here is the problem I'm having with this. I have a page that displays a list of items. I have a 'search' textbox and a submit button in an HTML form. When the user enters text in the textbox and clicks the search button or uses the enter key, the page posts the form data via HTML GET, and returns the first eight records found. The page then displays page links for additional pages. The problems is that when the user clicks a page link, the form data is all blank, and my filter information is lost (the form isn't posted with the form value when using these links). So, I end up displaying a blank list of items (blank searches returns zero results) instead of paging the data.
By adding the check for the button name in my form data, I could determine whether or not to simply page the data, or do a new look up.
I wouldn't rely on this. There are plenty of documented bugs with this scenario. Just add a hidden field with name='submit'. That way it wouldn't be too hard to recode the backend.
<input type='hidden' name='submit' value='FTSearchButton'/>
So, I researched this last night and almost got somewhere. Then this morning, I really did get somewhere and here's where I ended up.
Apparently the W3C standards for form submission are pretty lax when describing the functionality as it relates to the Enter button and submitting forms. It seems they determined that
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
So that leaves a lot of wiggle room for the browser makers. Today, virtually all browsers support using the Enter key to submit a form, whether the form contains one or more single line text input boxes.
The problem I'm having is more or less unique to Internet Explorer, and only when the form contains one, single-line text input control. For whatever reason, Microsoft decided that when Internet Explorer submits a form like this, it doesn't include the submit button's name/value pair in the post body. However, it does include the button's name/value pair if the user clicks the submit button --or-- uses the Enter key, and the form contains more than one single-line text input control.
So, the only solution I can think of or find suggested is to add a second single-line text input to my form, and then set the the style to
visibility: hidden; display: none;
My form now has two single-line text input controls, so the form will post with the name/value pair in the form body, regardless of whether or not the user used the Enter key or clicked the submit button.
So, we have a workaround that was discovered by ASP.NET developers. It seems the key/value pair is required by ASP.NET web-forms to fire the click event, so this work around isn't something new, albeit not my favorite way to do things.

Saving checkbox state on form post problem

I'm having problems setting the unchecked state of checkboxes upon form post. I have over 1000 checkboxes and so far i am able to check each checkbox n save there checked state. My problem however is unchecking the checkboxes.
I'm not having problems saving the checked state of each checkbox after form is posted. My problem is unchecking values then having that unchecked state saved after form post.
I'm also using paging on the page as shown in the code below (Values of submit buttons are parameters of a stored procedure)-
<center><input id="buttonStyle" type="submit" name="Page" value="#">
<% for i = 97 to 122 %>
<input id="buttonStyle" type="submit" name="Page" value="<%=CHR(i) %>">
<% next %></center>
<input id="buttonStyle" type="submit" name="Page" value="View All">
I need to save my checked state as I view each letter. So far thanks to the help of shadowwizard I am able to save checked and unchecked states of checkboxes if I click view all button. However the problem now is that when i click another letter (e.g - a, b, c) any checked state is removed when clicking view all.
<%
Dim tempArray
Dim checkArray
Dim temphiddenArray
Dim hiddenArray
'CheckBox Selection Array
if len(Request.Form("selectedRecord")) > 0 then tempArray = split(Request.Form("selectedRecord"), ",")
if isarray(tempArray) then
redim checkArray(ubound(tempArray))
'Create CheckArray ARRAY
for i = lbound(tempArray) to ubound(tempArray)
checkArray(i) = trim(tempArray(i))
next
'Hidden Array check
if len(request.Form("hiddenArray")) > 0 then temphiddenArray = split(request.Form("hiddenArray"), ",")
if isarray(temphiddenArray) then
redim hiddenArray(ubound(temphiddenArray))
for i = lbound(hiddenArray) to ubound(hiddenArray)
hiddenArray(i) = trim(temphiddenArray(i))
Session("LastCheck_"&i) = hiddenArray(i)
next
if ubound(hiddenArray) >= ubound(checkArray) then
for i = lbound(hiddenArray) to ubound(hiddenArray)
Session("CheckBox_"&(Session("LastCheck_"&i))) = ""
next
end if
end if
for i = lbound(checkArray) to ubound(checkArray)
Session("CheckBox_"&checkArray(i)) = "Checked"
%>
<input type="hidden" name="hiddenArray" value="<%=checkArray(i) %>">
<%
next
else
Session("CheckBox_"&request.Form("hiddenArray")) = ""
end if
%>
<% while not objRS.EOF %>
<input type="checkbox" name="selectedRecord" value="<%=objRS("Id") %>" <%=Session("CheckBox_"&objRS("Id")) %>>
objRS.MoveNext
wend
You're going through whole forest instead of climbing a short tree, or in other words making something simple terribly complicated.
What you need is this function:
<%
Function WasCheckedByUser(id)
Dim x
WasCheckedByUser = "checked=""checked"""
For x=1 To Request.Form("selectedRecord").Count
If Trim(Request.Form("selectedRecord").Item(x))=Trim(id) Then
Exit Function
End If
Next
WasCheckedByUser = ""
End Function
%>
Then use it like this:
<input type="checkbox" name="selectedRecord" value="<%=objRS("Id") %>" <%=WasCheckedByUser(objRS("Id")) %>/>
No need in arrays, no need in Session variables. Just simple iteration over the posted values (which are the values of the checked checkboxes) and if certain value is there, it means the corresponding checkbox should be checked, otherwise leave it unchecked.
Edit: you lose the "state" because when you click specific letter, you send to the browser only part of the checkboxes - so the previous value is indeed "lost" for good.
The most simple way to fix that is to send all checkboxes to the browser - always - and using simple style hide those that you currently don't send at all.
So, you'll have to change the SQL used to populate objRS to always select all, and change the loop to this:
<%
Do Until objRS.EOF
Response.Write("<input type=""checkbox"" name=""selectedRecord"" value=""" & objRS("Id") & """ " & WasCheckedByUser(objRS("Id")))
If Len(Request.Form("Page"))=1 And Trim(Left(objRS("Id"), 1))<>Trim(Request.Form("Page")) Then
Response.Write(" style=""display: none;""")
End If
Response.Write(" />")
objRS.MoveNext
Loop
%>
As far as I can see it should work and now preserve the state even for the hidden checkboxes.
check the resulting source code to see what it generated.
From what I can see, one problem would be that only checked checkboxes are posted when you submit a form, so if you originally have 10 checkboxes and check 3 of them and post, only those 3 will post back (and from the code, I guess only those 3 checkboxes would display after you submit, all of them checked).
You'd need to save all the checkboxes in the first run (say, with a default empty value like space), and then just change their session values when they're checked
The checkboxes are they actual items such as a category or option?
The reason i ask is that if you're setting checkboxes, how are these checkboxes defined? are they static fields or are they dynamic. I hope dynamic.
Here's how you can get things going.
Create a table called news (newsid, newstxt)
Create a table called categories (catid, catxt)
Create a table called NewscatSelected (ncsid, newsid, catid)to store check boxes of selected categories with the related newsid
Checkbox page form (cb1.asp)
Send the newsid as a query string to page (cb1.asp?newsid=34)
Dynamically list all categories as checkboxes, and get all records from NewscatSelected and pair them up. Any items that exist in the table NewscatSelected will be checked. They will have the same name but with an underscore and the numeric value of the category (cbt_34) to distinguish them easily
3.
Update Page Form (cb2.asp)
Upon getting querystring delete any existing values for the newsid sent to avoid duplicates
Insert the new checked values into the table called "NewscatSelected"
Redirect back to (cb1.asp?newsid=34) and new values will be checked.
See image below
I just posed an answer to this problem here:
how to implement a check box in classic asp
It's specifically designed for non-sequentially numbered, dynamically created checkboxes which require passing both a unique ID value and either checked or unchecked.
The solution does require a hidden field for each check box, but it does not use Javascript or any client side programming.
As the previous answer states, checkboxes do not get posted back when they are unchecked, so you have nothing in the request object that represents unchecked ones, which is fine if you know everything you are expecting to be posted back, but if it's all dynamic then it's not much use.
One workaround i've used before is to use hidden fields for the actual data, and use the checkboxes to control (via JS) the value's of the associated hidden fields, however I don't know how that solution would perform if you have 1000's of them on a page!