Adding a database populated dropdown Razor - asp.net

just started learning to make dynamic pages with WebMatrix and have run into a road block. (Long history of static html and some php using notepad++, but this is new to me.)
In short: I'm trying to give people the option of creating a new team entry in the database OR joining an existing team from a html helper dropdown list populated from the database. I've been trying various ways of doing this for the better part of two days and can't seem to figure it out after extensive searchers here and on ASP.net. I'm also hoping to figure out how to allow either the creation of a new team or joining an existing team already in the DB on the same page without getting commas inserted into the database.
I've removed all my attempts at a dropdown and am sharing what currently works without the html.dropdown:
#{
Validation.RequireField("FName", "Your first name is required");
Validation.RequireField("LName", "Your last name is required");
Validation.RequireField("Team", "A team is required to play");
Validation.RequireField("Pledge", "You must donate to play.");
var db = Database.Open("BBBT");
var FName = Request.Form["FName"];
var LName = Request.Form["LName"];
var Team = Request.Form["Team"];
var Pledge = Request.Form["Pledge"];
if (IsPost && Validation.IsValid()) {
if(ModelState.IsValid) {
var insertQuery = "INSERT INTO Players (FName, LName, Team, Pledge) " +
"VALUES (#0, #1, #2, #3)";
db.Execute(insertQuery, FName, LName, Team, Pledge);
Response.Redirect("~/ListTeams");
}
}
}
....Snip....
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
#Html.ValidationSummary("Errors with your submission:")
<form method="post" action="">
<fieldset>
<legend>Join the fun!</legend>
<div>
<label>First Name:</label>
<input name="FName" type="text" size="50" value="#FName" />
</div>
<div>
<label>Last Name:</label>
<input name="LName" type="text" size="50" value="#LName" />
</div>
<div>
<label>Create a Team</label>
<input name="Team" type="text" size="50" value="#Team" />
</div>
<div>
<label>Or Joing an Existing Team</label>
<!-- This is where I would like to put the Dropdown list-->
#Html.DropDownList
</div>
<div>
<label>Pledge:</label>
<input name="Pledge" type="text" size="50" value="#Pledge" />
</div>
<div>
<label> </label>
<input type="submit" value="Insert" class="submit" />
</div>
</fieldset>
</form>
</body>
</html>
Any direction would be greatly appreciated!
Thank you.

Your will be getting the result in two steps. First Generate the List, then display it.
In the code block at the top of the page add this code
List<string> Teams = new List<string>();
foreach(var row in db.Query("SELECT DISTINCT Team FROM Players"))
{
Teams.Add(row.Team);
}
and in the place you want the dropdown populate the list
<select name="Team">
#foreach(string Teamname in Teams)
{
<option value="#Teamname ">#Teamname </option>
}
</select>
EDIT:
<select name="Team" id="TeamDropdown" onchange="toggleteamcreation()">
#foreach(string Teamname in Teams)
{
<option value="#Teamname ">#Teamname </option>
}
<option value"New">Create New Team</option>
</select>
<script>
function toggleteamcreation(){
if(document.getElementById('TeamDropdown').value=="New"){
document.getElementById('Create_New_Team').style.display="block";
}
else{
document.getElementById('Create_New_Team').style.display="none";
}
}
</script>
<div id="Create_New_Team" style="display:none">
<label>Create a Team</label>
<input name="Team" type="text" size="50" value="#Team" />
</div>

Related

after postback of data to the dropdown the data is repeated

I've a form with textbox and two dropdowns. I am using this form for insert/details/edit of data. Initially for insert data, the form is working fine. But when I retrieve data from database, the dropdown values are repeated i.e., the retrieved value is repeated in the dropdown again.
My code::
<div class="form-group">
<label>Name</label><span class="required">*</span>
<input type="text" class="form-control" maxlength="200" runat="server" id="txtEmpName" autocomplete="off" />
</div>
<div class="form-group">
<label>Gender</label><span class="required">*</span>
<select class="form-control" id="selectEmpGender" runat="server" style="height: 34px;">
<option value="0">MALE</option>
<option value="1">FEMALE</option>
<option value="2">UNKNOWN</option>
</select>
</div>
<div class="form-group">
<label>Marital Status</label>
<select class="form-control" id="selectEmpMarried" runat="server" style="height: 34px;">
<option value="0">BACHELOR</option>
<option value="1">MARRIED</option>
<option value="2">DIVORCED</option>
</select>
</div>
<div class="form-group">
<div class="col-md-4">
<asp:Button ID="btnAddFamMem" runat="server" Text="ADD" OnClick="btnAddFamMem_Click" />
</div>
</div>
I am showing the data from grid view on selectedIndexChange method as ::
protected void famGrid_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = famGrid.SelectedRow;
txtEmpName.Value = gvr.Cells[1].Text == " " ? null : gvr.Cells[1].Text;
selectEmpGender.Items[selectEmpGender.SelectedIndex].Text = gvr.Cells[2].Text == " " ? null : gvr.Cells[2].Text;
selectEmpMarried.Items[selectEmpMarried.SelectedIndex].Text = gvr.Cells[3].Text == " " ? null : gvr.Cells[3].Text;
}
Please see the attached image, the image is of the data after I retrieved the inserted data from grid view for edit/details.
The retrieved value for selectEmpGender is UNKNOWN, it is repeated in the dropdown and the option MALE is not showing. Similarly, the retrieved value of selectEmpMarried is MARRIED which is repeating in the dropdown and BACHELOR option is not showing. Why is it so?
I think you dont want to change the text of the selected item but you want to select the corrrect item:
string gender = gvr.Cells[1].Text;
ListItem genderItem = selectEmpGender.Items.FindByText(gender);
if(genderItem != null)
selectEmpGender.SelectedIndex = selectEmpGender.Items.IndexOf(genderItem);
// same for the other
After inserting or updating employee details, clear drop-down and then bind its details.
After inserting,
txtName.Text = string.Empty;
selectEmpGender.SelectedIndex = -1;
selectEmpMarried.SelectedIndex = -1;
While editing,
bind datas from genderItem
selectEmpGender.SelectedItem.Value= genderItem.gender;

spring+ thymeleaf unable to update

Hi I am working with spring MVC and thymeleaf and I am not able to update data from my controller as I have following code.The main problem I am facing is that my put method is not getting called.
#GetMapping("/{id}/edit")
public String editUser(#PathVariable("id") int id, Model model) {
logger.info("++++++++++++[edit User]\n\n" + userService.findById(id));
model.addAttribute("user", userService.findById(id));
return "user/edit";
}
#PutMapping("/{id}/edit")
public String updateUser(#PathVariable("id") int id, #ModelAttribute("user") User user, Model model) {
logger.info("\n\n+++++++++++++++++inside Update");
User toUpdate = userService.findById(user.getId());
user.setUserName(user.getUserName() != null ? user.getUserName() : toUpdate.getUserName());
user.setName(user.getName() != null ? user.getName() : toUpdate.getName());
logger.info(user.toString());
userService.updateUser(user);
model.addAttribute("user", userService.findById(user.getId()));
return "redirect:/user/" + id;
}
and my html page
<form action="#" th:action="#{/user/__${user.id}__}" method="put"
th:object="${user}">
<div class="form-group">
<label for="txtUserName">User-name</label> <input
class="form-control" id="txtUserName" placeholder="User Name"
th:feild="${user.userName}" />
</div>
<div class="form-group">
<label for="txtName">First Name</label> <input
class="form-control" id="txtName" placeholder="Full Name"
th:feild="${user.name}" />
</div>
<div class="form-group">
<label for="calDob">Date of Birth</label> <input
class="form-control" id="calDob" placeholder="dd/MM/yyyy" />
</div>
<button type="submit" th:method="put" class="btn btn-success">Update</button>
<a href="#" th:href="#{/user/__${user.id}__}"
class="btn btn-primary">Cancel</a> <a th:method="delete"
href="javascript:deleteUser('${user.id}');" class="btn btn-danger">Delete</a>
</form>
any help will be usefull thanks
PUT is not a valid argument for method attibute of the form tag. See HTML specification.
Valid methods are GET and POST. And as it's not a REST API, you can use POST method to update.
So just update your mapping from:
#PutMapping("/{id}/edit")
to
#PostMapping("/{id}/edit")
And form tag to:
<form action="#" th:action="#{/user/__${user.id}__}/edit" method="post" th:object="${user}">

Html.BeginForm loses routeValues on submit

I have a page that displays a list of people. It can be sorted on first and last name. To search for people, I have the following Razor form:
#using (Html.BeginForm("Index", "Persons", new { sort = ViewBag.Sort }, FormMethod.Get))
{
<p>
Search: #Html.TextBox("search", ViewBag.Search as string)
<input type="submit" value="Search" />
</p>
}
ViewBag.Search and ViewBag.Sort contains the last used search and sort routeValues. When I sort the list of people on first name, the form gets rendered in HTML like this:
<form action="/persons?sort=firstname" method="get">
<p>
Search: <input id="search" name="search" type="text" value="" />
<input type="submit" value="Search" />
</p>
</form>
As intended, ?sort=firstname is included in the action. However, when I press the submit button (Search), the sort parameter is lost. The new url only has ?search=.... How can I fix this?
When you look at the output html you would get something like this :
<form action="/persons/index?sort=asc" method="get">
<p>
<input type="text" name="search" />
<input type="submit" value="Search" />
</p>
</form>
This seems completely legit, you would expect a behaviour like appending the query of post inputs. However this is limited by HTTP specification. The query string of a form post action wont be appended. That is why your query parameters wont work at your server side. However i what would expect from the Asp.net to get the parameters for the form to the hidden fields automatically which it doesnt right now.
As a proper solution you have to put the input , in the form , so you can use hidden field to do this like :
#using (Html.BeginForm("Index", "Persons", FormMethod.Get))
{
#Html.Hidden("sort",ViewBag.Sort)
<p>
Search: #Html.TextBox("search", ViewBag.Search as string)
<input type="submit" value="Search" />
</p>
}
You need to store the value of sort somewhere in the form, in order for it to be included as part of the submit. You could try a hidden input:
#using (Html.BeginForm("Index", "Persons"))
{
<input type="hidden" id="sort" value="firstname" />
<p>
Search: #Html.TextBox("search", ViewBag.Search as string)
<input type="submit" value="Search" />
</p>
}
You may need to tweak how the value of sort is retrieved from, I put firstname as an example, but when you submit the form, sort will be included in the payload e.g.
[HttpPost]
public ActionResult Index(string sort, string search)
{
}

jquerymobile controlgroup not displaying properly

I'm updating website and gradually changing all bits over to jquerymobile to make it more phone friendly.
I had a page where a user can select either a specific month or a date range. I toggled between them using some javascript. However, since changing things the display:block etc doesn't seem to work properly. It displays them out of position. The input fields are now displayed above the selector when you toggle between them. Please see http://jsfiddle.net/pfLme/1/
Obviously I would like to get them into the correct position.
(The next task will be to try and get Datepicker working - if anyone fancies pointing me in the right direction for that)
Thank you.
(code is all on jsfiddle, but stackoverflow tells me i need to include it here too)
function showType(allornone) {
if (allornone == '1month')
{
document.getElementById('btwdateselector').style.display = 'none';
document.getElementById('monthselector').style.display = 'block';
document.getElementById('datestart').value = '';
document.getElementById('dateend').value = '';
}
if (allornone == '2dates')
{
document.getElementById('btwdateselector').style.display = 'block';
document.getElementById('monthselector').style.display = 'none';
}
} //end function
...I realise now of course that I have to get used to thinking about & taking advantage of the jquery side of jquery mobile too.
So far I came up with
$(document).on('click', '#certainmonth', function(a) {
$('#monthselector').hide();});
$(document).on('click', '#btwdates', function(a) {
$('#btwdateselector').show();});
I'm not sure yet how to include the if statement and toggle between the show and hide.
The error was only occurring in Firefox 27.0.1
Solution was to change <fieldset data-type="controlgroup"> to <div data-type="controlgroup"> around the radioboxes. Thanks to Omar for the help.
http://jsfiddle.net/pfLme/11/
<form action="page.php" name="mileageform" class="responsive_block" data-ajax="false">
<div data-role="controlgroup">
<legend>Should be at TOP</legend>
<input type="radio" name="searchtype" value="certainmonth" id="certainmonth" checked="checked" />
<label for="certainmonth">Mileage for certain month</label>
<input type="radio" name="searchtype" value="btwdates" id="btwdates" />
<label for="btwdates">Mileage between two dates</label>
</div>
<fieldset id="monthselector" data-role="controlgroup" data-type="horizontal">
<select name="month" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="year" data-native-menu="false">
<option value="2000">2000</option>
<option value="2001">2001</option>
</select>
</fieldset>
<fieldset id="btwdateselector" class="ui-screen-hidden">
<div class="ui-field-contain">
<label for="datestart">Start Date:</label>
<input type="date" id="datestart" name="datestart" placeholder="dd/mm/yyyy" />
</div>
<div class="ui-field-contain">
<label for="dateend">End Date:</label>
<input type="date" id="dateend" name="dateend" placeholder="dd/mm/yyyy" />
</div>
</fieldset>
<input type="submit" onclick="return checkForm();" value="Display Mileage" />
</form>
$(document).on('change', '#certainmonth, #btwdates', function (a) {
$('#monthselector').toggleClass("ui-screen-hidden");
$('#btwdateselector').toggleClass("ui-screen-hidden");
});

add custom data to POST

I have a webpage that has 3 file inputs. There are specific fields on the form that needs to be sent when user uploads the file. I am not able to figure out how do i add custom data to my POST and how do i retrieve it back on the server. This is how my code looks like:
ASPX Page with 3 file inputs and other text boxes/dropdowns:
<form action="FilesUploader.ashx" method="post">
<div id="dvNewAttachment1">
<span>Attachment Type</span>
<select id="ddlAttachmentType1">
<option>T1</option>
<option>T2</option>
<option>T3</option>
</select>
<span>Description</span>
<input id="txtDesc1" />
<select id="ddlApproval1">
<option>Yes</option>
<option>No</option>
</select>
<input id="fileUploader1" type="file" runat="server" />
</div>
<br />
---------------
<div id="dvNewAttachment2">
<span>Attachment Type</span>
<select id="ddlAttachmentType2">
<option>T1</option>
<option>T2</option>
<option>T3</option>
</select>
<span>Description</span>
<input id="txtDesc2" />
<select id="ddlApproval2">
<option>Yes</option>
<option>No</option>
</select>
<input id="fileUploader2" type="file" runat="server" />
</div>
<br />
-------------------------------
<div id="dvNewAttachment3">
<span>Attachment Type</span>
<select id="ddlAttachmentType3">
<option>T1</option>
<option>T2</option>
<option>T3</option>
</select>
<span>Description</span>
<input id="txtDesc3" />
<select id="ddlApproval3">
<option>Yes</option>
<option>No</option>
</select>
<input id="fileUploader3" type="file" runat="server" />
</div>
<input type="submit" />
</form>
This is how my handler looks like:
public void ProcessRequest(HttpContext context)
{
HttpPostedFile myFile = context.Request.Files[0];
int nFileLen = myFile.ContentLength;
byte[] buffer = new byte[nFileLen];
using (BinaryReader br = new BinaryReader(myFile.InputStream))
{
br.Read(buffer, 0, buffer.Length);
}
}
As you can see i have 3 uploads and each has Attachment Type and description associated with it which i need to retrieve for each input file in my handler.
Right now i am just processing file from the first input but later i am going to loop thru the inputs and process them.
If your handler do not receive files that you place in file uploaders then your form needs to have additional attribute like this:
<form action="FilesUploader.ashx" method="post" enctype="multipart/form-data">
In order to get values from dropdowns on server you need to provide a name attribute to them:
<select id="ddlApproval1" name="ddlApproval1">
<option>Yes</option>
<option>No</option>
</select>

Resources