I have a bunch of select tags whose option value I want to save even after the form is submitted. Currently, the value resets to the top value after submission.
I tried the following method but it doesn't work! It selects the last option of the for loop in this code.
<select class="form-control" id="selYear" name="selYear">
#for (var i = 2016; i > 1999; i--){
if(IsPost){
<option value="#i" selected='#(Request.Form["selYear"].Equals(i.ToString()) ? "selected" : "")'>#i</option>
}
else {
<option value="#i" >#i</option>
}
}
</select>
Does anyone have a solution for this? Please provide some sample codes/examples.
You are actually selecting every line and the browser decides to use the last. Modify that line to look something like this:
<option value="#i" #(Request.Form["selYear"].Equals(i.ToString()) ?
"selected" : "")>#i</option>
Related
I have a Blazor app that populates 6 select option dropdowns with data from DB. Three of these are populated with date and time from a string list.
When I select a date and time it is not displayed in the dropdown box. After selecting a date time the dropdown is blank, but the value is actually selected and binding works. It's just not displayed.
If I remove "bind=#..." it displays correctly.
Have anyone else experienced this, and how did you solve it?
<select bind="#Innput.Klokkeslett1">
<option value="#(0)">Tid1</option>
#foreach (var tid1 in tidListe)
{
<option value="#tid1">#tid1</option>
}
</select>
Two things to note, select uses a string value, and that value needs to match the option value.
So, if your field Innput.Klokkeslett1 is a DateTime, you will need to use a property to handle the binding / conversion between string and DateTime.
If you ensure you use an explicit date format for the option values, and your property returns it's value in the same date format, then the select will be able to match it's value to one of it's option values and display the corresponding text, which can be formatted any way you like.
<select bind="#MySelectProxy">
<option value="#(0)">Tid1</option>
#foreach (var tid1 in tidListe)
{
<option value="#tid1.ToString("yyyy-MM-dd HH:mm:ss")">#tid1</option>
}
</select>
#functions
{
string MySelectProxy {
get => Innput.Klokkeslett1.ToString("yyyy-MM-dd HH:mm:ss");
set => DateTime.TryParse(value, out Innput.Klokkeslett1);
}
}
<select onchange="#ComboSelectionChanged">
<option value="0" selected>
#list[0]
</option>
#for (int i = 1; i < list.Count; i++)
{
<option value="#i">
#list[i]
</option>
}
</select>
public void ComboSelectionChanged(UIChangeEventArgs e)
{
if (int.TryParse(e.Value.ToString(), out int index))
{
SelectedStyleIndex = index
//now you know which one is selected
}
}
I have used a dropdownlist with static values before and was able to manually disable some item in the list (As i wanted headers for each set of items). I am looking to do the same dynamically once i get the list from the database.
Looking forward on including a header functionality for the list from the database.
The headers and the list would be obtained from the database.
Below is the static code that i used to include this feature.
<select class="combobox form-control" id="sel" name="iArea">
<option value="" disabled selected style="display:none">Select an option</option>
<option value="" disabled>Health</option> <!-- Disabled Header -->
<option value="WP">   Creating a world wide network, bringing people together by not having any distinction by race, caste or religion?</option>
<option value="FL">   Tracking down loved one's in a crowded or emergency situation at a cost effective manner?</option>
<!-- Enabled List for a header above -->
<option value="Others">   Others</option>
<option value="OfBT" disabled>Social Service</option> <!-- Disabled Header -->
<option value="Others">   Helping the old folks get a place to stay?</option>
</select>
I wanted the same done dynamically, i am using #Html.DropDownListFor in the view page of my action in MVC architecture.
The table structure that i am using is as below. The summaries belong to a set, the header that i was looking at would be the set name. And the list of entities that falls under this set name would come under that header. The set name/ header would remain disabled, only for illustration. The entities corresponding to that set name can be selected/enabled in the dropdown list. I am using MVC 4 architecture.
Image of Database Table structure
Drop Down List screenshot for the table structure described above
You can do something like this:
IEnumerable<GroupedSelectListItem> item;
item = new List<GroupedSelectListItem> {
new GroupedSelectListItem() { Value="volvo", Text="Volvo", GroupName="Swedish Cars", GroupKey="1", Disabled=true },
new GroupedSelectListItem() { Value="saab", Text="Saab",GroupName="Swedish Cars", GroupKey="1" },
new GroupedSelectListItem() { Value="mercedes", Text="Mercedes", GroupName="German Cars", GroupKey="2" },
new GroupedSelectListItem() { Value="audi", Text="Audi", GroupName="German Cars", GroupKey="2",Selected=true }};
And then:
#Html.DropDownGroupList("Cars", item, "-- Select Car --",
new Dictionary<string, object>() {
{ "data-val", "true" },
{ "data-val-required", "The Car field is required." }
})
To get something like this:
<select data-val="true" data-val-required="The Car field is required." id="Cars" name="Cars" class="valid">
<option value="">-- Select Car --</option>
<optgroup label="Swedish Cars" value="1" disabled="">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup label="German Cars" value="2">
<option value="mercedes">Mercedes</option>
<option selected="selected" value="audi">Audi</option>
</optgroup>
</select>
#StephenMuecke, I ended up creating my HTML code in the MVC view, by looping. But wouldn't have been possible without you guys guiding, me being a beginner and all. I have explained the concept here; the List section would be obtained from the database. This worked perfectly, though i guess it may hit the performance, if the data for the drop down is a lot.
The Action Section in the controller
UserData.InnovateSection = new List<DropDownList>{new DropDownList { label = "Health", value = "Creating a world wide network, bringing people together by not having any distinction by race, caste or religion?" },
new DropDownList { label = "Health", value = "Tracking down loved one's in a crowded or emergency situation at a cost effective manner?" },
new DropDownList { label = "Social Service", value = "Others" }};
var headers = (from it in UserData.InnovateSection
select it.label).Distinct().ToList();
var headersLength = headers.Count;
int i = 0, k;
UserData.Innovate = new System.Text.StringBuilder();
while (i < headersLength)
{
k = 0;
foreach (var item in UserData.InnovateSection)
{
if (headers[i] == item.label && k == 0)
{
UserData.Innovate.Append("<optgroup label = " + "\"" + item.label + "\"" + ">");
k = 1;
}
if (headers[i] == item.label)
{
UserData.Innovate.Append("<option value= " + "\"" + item.value + "\"" + ">" + item.value + "</option>");
}
}
UserData.Innovate.Append("</optgroup>");
i++;
}
return View(UserData);
The HTML code in the view being rendered
<select class="combobox form-control" id="sel" name="IdeaArea">
<option value="" disabled selected style="display:none">Select an option</option>
#Html.Raw(#Model.Innovate) <!-- Model created goes inside the Raw tag to convert string to HTML DOM -->
</select>
And i got the custom dropdown that i was seeking, in the end. :)
I have a drop down list which contains 3 values:
Male
Female
Unspecified
Basically in my view, when I selected with male, female or unspecified, I want to change the data that I have in another combo box, e.g. the male users, the female users and the users who haven't given their gender.
List<User> users = new List<User>();
foreach (User user in ctspc.db.AllUsers.ToList())
{
users.Add(DAL.Getusers(user.UserId));
}
So here I get all the users, my problem is I need to use LINQ to sort out which type of gender I need to search, that bit I can handle, the problem I am having is that I am unable to retrieve the drop down list value.
I tried:
var x = Request.Params["cboGender"];
But I assume because the page hasn't loaded yet, it isn't able to get what the current value is, so basically what I am trying to do is have it so depending on the value in the list box at the time, I want it to recall my Create method and keep getting the selected value and updating the new list box.
Here I have the cshtml code
<select name="cboGender">
#foreach (var Gender in ViewBag.Genders)
{
<option value="#Gender.GenderId">#Gender.Name</option>
}
</select>
<select name="cboUser">
#foreach (var User in ViewBag.UsersByGender)
{
<option value="#User.UserId">#User.Username</option>
}
</select>
Any help on how I can do this would be great.
If I understand your problem correctly then, you can try one of the following methods to retrieve data.
e.g.
public ActionResult SomeAction(string cboGender)
or try using
string Gender= Request.QueryString["cboGender"];
or
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["cboGender"];
}
there is no other way to do this without js.
Oh, maybe you can create a button to sumbit the form,so your server side can get the value,
Request.Params["cboGender"] will effective. then filter user,render the page(it means refresh and bad experience ), is that your want?
I guess you used to do with asp.net WebForm.
In fact , WebForm framework also encapsulated with much js(JQuery) code.
the best way is : use ajax to post the genderId to server method like belowe
[HttpPost]
public JsonResult GetUserByGenderId(int? genderId)
{
var list = AllUsers.Where(a => a.genderId == genderId);// filter user
return Json(list);// return serialized json or
return Json(list.Select(a=>new { a.UserName,a.UserId }).Tolist());
}
and the ajax would receive this json to render the cboUser.
There are lots of ways to do this, but based on the way you've asked the question I think the easiest would be to do something along these lines:
1: Put a new combo-box into the page for each group of users, and hide them by default (note here I'm not a foreach like you are but that's just for brevity of the example):
<select id="cboGender" name="cboGender">
<option id="Male">Male</option>
<option id="Female">Female</option>
<option id="Unspecified">Unspecified</option>
</select>
<select id="cboMale" class="user-combo" name="user" hidden>
<option id="1">Oscar</option>
<option id="2">Leo</option>
</select>
<select id="cboFemale" class="user-combo" name="user" hidden>
<option id="3">Kristy</option>
<option id="4">Wendy</option>
</select>
<select id="cboUnspecified" class="user-combo" name="user" hidden>
<option id="5">Jamie</option>
<option id="6">Charlie</option>
</select>
2: Use jQuery to listen for changes to the "cboGender" combo box, then show the appropriate combo box in response:
var onGenderChanged = function() {
var gender = $genders.val();
// Hide all gender combo boxes...
$userCombos.hide();
// ... then show the one corresponding to the selection
$("#cbo" + gender).show();
};
Here's a JSBin which shows a working implementation.
The advantage of doing this is it saves you a "round-trip" to get the gender specific users each time the user changes.
Another alternative would be to load the users with an AJAX request when a gender is selected, but that's a bit more involved.
HTH
I'm wondering what the best practice is to select an option from a select field from my database.
I am pulling the data in from my model, but it seems like having an if in every line of code isnt the most efficient.
Here is my current code, is there a better way?
<select id="Downloads" name="Downloads">
<option value="Option1" <% if(Model.Downloads == "Option1"){ %>selected <% } %>>Option1</option>
<option value="Option2" <% if(Model.Downloads == "Option2"){ %>selected <% } %>>Option2</option>
<option value="Option3" <% if(Model.Downloads == "Option3"){ %>selected <% } %>>Option3</option>
</select>
I have 10 of these select boxes and just want to keep my code clean
Build a SelectList, or a collection of SelectListItems on your model, and then use use DropdownListFor:
#Html.DropDownListFor(x => x.Downloads, Model.DownloadOptions)
I suggest you add a css class to each select box.Then create an javascript array to save value of them. Following is a way to retrieve value of them and push them into javascript array.
var values =[];
$(".mySelectBox").each(function(i) {
//push to values array
});
i am using this demo:
http://www.emblematiq.com/lab/niceforms/demo/v20/niceforms.html
i would like to know which values the user has selected.
<select size="4" name="languages[]" id="languages" multiple="multiple">
<option value="English">English</option>
<option value="French">French</option>
<option value="Spanish">Spanish</option>
<option value="Italian">Italian</option>
<option value="Chinese">Chinese</option>
<option value="Japanese">Japanese</option>
<option value="Russian">Russian</option>
<option value="Esperanto">Esperanto</option>
</select>
the question is how do i return the values that were selected by the user?
I've put together a quick demo (using the select box structure from your example) here: http://jsfiddle.net/wp7sq/
So essentially, in my example I've created a simple function that gets which options the user selected, adds them to an array (just for convenience). So from here, you can output it to a string, or search your array, or do whatever you want using JavaScript using that array.
The relevant section is commented in the sample, and here's the jQuery code from my example:
var selectedLanguages = new Array();
jQuery('#languages option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
Try something like this:
ob = document.getElementById('languages');
for (var i = 0; i < ob.options.length; i++){
if (ob.options[ i ].selected){
alert(ob.options[ i ].value); //Do something useful here
}
}
$("#languages").value;should work