ASP MVC3 DropDownListFor with blank default option - c#

I'm populating a small set of drop down list items in my model list so:
SecSellerCodes = (from s in db.DropDownValues
where s.Field.Equals("SecSellerCd") &&
s.DisplayPage.Equals("Agent Create")
select s).Select(x => new SelectListItem
{
Text = x.DisplayValue,
Value = x.AllowedValue
}).Distinct().ToList();
I would like the user to be able to select from the list of items pulled from the query above, plus include a blank option at the top of the list in case they do not want this particular field populated.
Using the following helper, this works fine once the page loads/user saves to the database. However, if they need to reload the page and make adjustments, the blank string.Empty item is always selected (no matter the value in the table).
#Html.DropDownListFor(model => model.SecSellerCd, Model.SecSellerCodes, string.Empty)
Any idea which helper/technique to use to accomplish this?

In your model code you need to assign the selected value to model.SecSellerCd. So if you want them to make changes from previous selection then you need to save the selected value in the database as well.

Related

Set value of Asp DropDown List is not Working

I have an asp.net DropDownList that I use to filter a RadGrid. After the filter has been applied I can click on a row to edit the record on a separate page. I have a requirement to provide the ability, if the wrong row was selected, to return to the previous search page and display the same records with the same filter. I have taken care of the return and showing the same filtered records.
I also need to show the same value in the dropdown list that was chosen to create the filter. I am trying to do this using a session variable. The session variable gets created on the search click and I am trying to select the same item from the drop down using this code when the user returns to the search page.
string value = (Session["ComplaintType"] != null) ? Session["ComplaintType"].ToString() : String.Empty;
ddlComplaint.Items.FindByValue(value).Selected = true;
It is not working ant I get this error message: Object reference not set to an instance of an object.
Not sure why I am getting that error the string value is equal to the text value of the item selected from the Drop down??
I was able to solve this problem by setting the dropdownlist selected value in the BindDropDown method where I bind the database to the database. Once it was bound I could select a value from the database as the default value.

DisplayFor() to show what was selected from a drop down list

So drop down lists have value/text. The value is what I store in my database (as it's the primary key to a table that lists value/text to show in the drop down list). When I populate my drop down I use the value/text. When a user selects it stores the value (numeric) to the transaction table. This means when I read it back into my model I have the number value and not the text. However, after 24 hours of the selection I need to only display the text as they can't make changes. The issue is it's display the value (1, 2, 3, 4) instead of the actual text which would make more sense to humans.
Is there a way to convert this at the view level? The reason I ask is because my template branches off and acts as a display template and editor template because that's the functionality required on the page. So I easily show the selected value in the editor template sections via:
#Html.DropDownListFor(modelItem => item.RecordType, new SelectList(Model.RecordTypes, "RECORD_TYPE_ID", "RECORD_TYPE", item.RecordType)
but the display section has:
#Html.DisplayFor(modelItem => item.RecordType)
Which gives me the value number and not the text. Do I really have to make another field in my view model and populate per record the text as well as the value? As you can see from the DropDownListFor() I have the RecordTypes list that stores the value/text so can I use the value to find the text and display that from the template view via DisplayFor() or something other function?
One alternative might be:
#Html.DisplayFor(modelItem =>
Model.RecordTypes.FirstOrDefault(rt => rt.RECORD_TYPE_ID == item.RecordType))
UPDATE: as stated in the comment, the right approach ended up being:
#Model.RecordTypes.FirstOrDefault(rt => rt.RECORD_TYPE_ID == item.RecordType).RECORD_TYPE.ToString()
which simply displays the string value.
#Html.LabelFor(m => m.Action)
#Html.DisplayFor(m => m.ActionTypes.FirstOrDefault(c => c.Value == m.Action.ToString()).Text)
This works perfectly!

Best way to display data in a listbox from DB in C#

I have a local database, which holds records for cars, it has fields ID(ai, primary), plateNumber, Comments, ect..
Also I have a form with ListBox, button "Checked", and many text fields.
I am using winforms, and every time I run the application, constructor retrieves all the records from the db which have the bool field named "checked" == null, and displays the carnumbers in the Listview. When a specific plateNumber in that listBox is clicked, the other column data for the selected carPlate should appear in the textfields, but the
Problem is that there might be more records with the same plateNumber where "Checked" == null(true otherwise).
Question: how to keep the information about the specific plate number "behind the scenes" and when person clicks to select the platenumber from the listBox, it displays the data about the current(by id) platenumber in the form. Note that, if person clicks a "Checked" button on the form, it stores "TRUE" in the DB "checked" field and removes the specific carPlate from the listBox, and the next time application is launched it won't display that specific ID. In web I use hidden fields with javascript to achieve this, in C# I'm not aware how you keep information like that, I'm leaning towards arrays?
Thanks.
ListViews are populated with ListViewItems. The ListViewItem class has a Tag property, where you can store anything you want. Your "hidden" or "behind the scenes" data can be stored there.

ASP.NET Html.ListBoxFor always has ALL options selected when page loads

I'm building a very simple form to edit the properties of an object. One of the properties is a list of other objects that are associated with it, so I'm using a two-list system: on the left, a list of currently associated objects, and on the right, a list of objects that are available to add; Add and Remove buttons underneath apply the relevant operations to the highlighted items in the relevant lists. Simple enough.
It's all working fine, except for one thing: when the page loads, all items in both lists are selected, even when I specifically set Selected = false when creating the items with which to populate the lists. This means that if the user submits the form without touching the lists, everything in the "current" list is removed, and everything in the "available" list is added. As they're multi-select listboxes, there's no dummy option for the user to select, so this issue is forcing them to always remove at least one of the current items and add at least one of the available items. Even if there were a dummy item, it forces the user to go and select it, and if they forget, their lists get messed up.
[Edited to add:]
An example of what the controller method is doing:
[HttpGet]
public ActionResult EditForm(int objectId)
{
MyObject objectToEdit = _objectStore.GetObject(objectId);
ObjectEditViewModel viewModel = new ObjectEditViewModel();
viewModel.Object = objectToEdit;
viewModel.AssociatedItemSelectList = objectToEdit.AssociatedItems.Select(o => new SelectListItem { Text = o.Name, Value = o.Id, Selected = false });
viewModel.AvailableItemSelectList = _itemStore.GetAllItems().Where(o => !objectToEdit.AssociatedItems.Contains(o))
.Select(o => new SelectListItem { Text = o.Name, Value = o.Id, Selected = false });
return View(viewModel);
}
...and the view just has
#Html.ListBoxFor(m => m.ItemsToAdd, Model.AvailableItemSelectList)
and
#Html.ListBoxFor(m => m.ItemsToRemove, Model.AssociatedItemSelectList)
in the relevant places. When the page loads, every option in the select listboxes has the form:
<option selected="selected" value="281">Example Item</option>
How are the items being selected between the creation of the list and the rendering of the page? How do I stop it? Or, failing that, how can I de-select them immediately on page load so that it appears to the user as if they start unselected? I have a fix that will make the page look like it should, but I'd like to get to the root of this problem.
This might be a late reply, but I think the reason has something to do with the binding of the listbox to the object it is referencing. For instance if you were to use ListBox instead of ListBoxFor and give ListBox a name so that it doesn't bind to anything, the items in the listbox won't be selected initially. But if you were to give it a name that would cause it to be bound the items will be selected. I was having the same trouble as you were and just happened to come across this through trial and error :-)
I had the same issue and realized that it was in my model property that I was setting the selected item(s) to all.
It is hard without seeing your model to know what's going on, but check your definition of ItemsToAdd and AvailableItemSelectList and respectively for the other list and make sure you are not doing any .Select...ToList() there.
public List<SelectListItem> AvailableItemSelectList{
get
{
var items = //get your items from repository
return items;
}
}
public List<string> ItemsToAdd{
get{ //make sure you are not setting anything here}
set{}
}
You can also do like this to un-select your all listbox items on page load:
$(document).ready(function () {
$("#listbox").find("option").attr("selected", false);
});

Set selected value in a SharePoint Dropdown list

We are using SharePoint 2010 Foundation.
We have an item in a list that is a dropdown with values from another list.
When we access the list as a SharePoint list it works fine, we can select a value, save the list, the next time we access the list the correct value is selected.
We have programmed a form that will updated the list. When we pull up the form, select a value and save it, we can see by accessing the list directly that the value has been saved.
However, when we pull up the form again it is the first item in the list that is selected. Have tried storing the selected value is a temp variable before binding the list but have not been able to get it to work. Anyone know how to fix this?
We found a solution.
The trick was to get the number that is the first part of the ToString of the SPListItem, before binding the list.
Then use that number to set the selected value after the list is bound
Parameters:
SPListItem currentItem, string fieldName
Code:
string selectedValue = currentItem[fieldName].ToString().Substring(0,1);
//... Bind list
ddlLookup.SelectedValue = selectedValue;

Categories

Resources