I have a list of a certain object, each object contains fields. I need to do a DropDownListFor or DropDownList for that field within that object but its not binding
I initially tried this with a List and this works fine for binding to a normal object field. I then tried converting to SelectList() by doing
#Html.DropDownListFor(model => Model.MyListOfObjects[i].FieldName, new SelectList(Model.MySelectList, "Value", "Text"))
I then tried to set the "Selected" property on the SelectListItem I needed to be selected but still no luck
for (var i = 0; i < Model.MyListOfObjects.Count; i++){
#Html.DropDownListFor(model => Model.MyListOfObjects[i].FieldName, Model.MySelectList)
}
Model.MySelectList is List<SelectListItem>
public List<MyCustomObject> MyListOfObjects {get;set;} //populated
public class MyCustomObject{
public string FieldName {get;set;}
}
So in the end, I need the value of Model.MyListOfObjects[i].FieldName tp be selected from the Model.MySelectList(). The value in the select list does match so I cant see whats wrong
Thank you. Appreciate any help
EDIT: I know I can use "EditorFor" templates for the object used in Model.MyListOfObjects but I would prefer to avoid it if possible as I am using that object with other things so if I need another version of the object in editorfor then I wouldnt be able to do it. As a last resort though, I will just have to change the object to a unique one and go down the editorfor route
selectListItem contains text and value.
You need to bind value field to dropdown not text field.
i.e. model => Model.MyListOfObjects[i].FieldValue
Check This will help you
Related
I'd appreciate if someone could help with my issue.
I have an entity with field PAYMENT_CURRENCIES of string type, that should store comma separated values, i.e. "USD,EUR,AED" (or any other separation char).
In my View:
#Html.Kendo().MultiSelectFor(model => model.Contract.PAYMENT_CURRENCIES).BindTo(context.Currencies).DataTextField("CODE").DataValueField("CODE").Placeholder("Add currency...")
The problem is when I submit the form i receive only first selected value in the Controller.
I would not like to change the datatype of the field for IEnumerable.
Is there a way to receive all selected values as a string with some separator?
Thanks a lot
I don't think that you can automatically convert your multi select input value(s) to a single string.
So what you can do is:
Use a viewModel (ContractViewModel) which contains a List
Or use javascript to "convert" your input value(s) to a single string separated with any separator you want
Add an array-property to your model:
public string[] PAYMENT_CURRENCIES_LIST
{
get
{
return PAYMENT_CURRENCIES?.Split(',');
}
set
{
PAYMENT_CURRENCIES = string.Join(",", value);
}
}
Then use this property in your view:
#Html.Kendo().MultiSelectFor(model => model.Contract.PAYMENT_CURRENCIES)...
So the array-property maps to the Kendo-Multiselect and translates the values to/from the original field.
I had the same requirement as yours, & couldn't find a decent solution, That's how I solved it:
Create a new Property in your ViewModel public List<string> SelectedCurrencies { get; set; }
Configure your MultiSelect Kendo helper to bind to the newly created property #Html.Kendo().MultiSelectFor(model => model.SelectedCurrencies)
.BindTo(context.Currencies)
.DataTextField("CODE")
.DataValueField("CODE")
.Placeholder("Add currency...")
To Save: Now when you hit your action method, just set your comma separated field PAYMENT_CURRENCIES = string.Join(",", viewModel.SelectedCurrrencies);
To Read: SelectedCurrencies = PAYMENT_CURRENCIES.Split(',').ToList();
I'm looking into creating an Edit page for a Company object that has multiple categories (that are predefined in a list). I have the list being sent through the ViewBag, and have the categories that the user selected in the Create page in an Array thanks to a ViewModel.
I can't figure out a way to have the ListBox prepopulate with the multiple values in my array. I was playing around with jQuery and was able to get one of the values to be selected, but when I try more than one nothing shows up. Any ideas?
#Html.ListBox("Category", new SelectList(ViewBag.Category, "Text", "Value"))
The SelectListItem object has a Selected property to indicate this. So I guess it would come down to how you build the SelectList. Currently you do this:
new SelectList(ViewBag.Category, "Text", "Value")
Which works, but gives you no control over the individual SelectListItems. Instead of building a SelectList, you can build an IEnumerable<SelectListItem> using the same method overload. Initially that might look like this:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value
});
At this point you have more control over the individual items. Now it's just a matter of determining which ones should be selected. How do you determine that? Is it a property on the Category object? Something like this?:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value,
Selected = c.Selected
});
Or perhaps some other condition?:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value,
Selected = c.SomeValue == SomeCondition
});
How you determine that is up to you, and ideally something you can logically add to the backing model being used here.
I have a drop down on my site that has a number of languages in it. When a user selects a different language, the page text reloads to that language. I would like the language drop down to change to reflect that by specifying the selected index of the selected language. However when ever I do this, the drop down in HTML does not change and always displays the first item in the list.
I have the following ViewModel :
public class BaseViewModel
{
public BaseViewModel()
{
}
public IEnumerable<SelectListItem> LanguageSelectListItems { get; set; }
}
The LanguageSelectListItems property is populated successfully when I construct a list of SelectListItems. When this is passed into the view, the selected language SelectListItem is set to true - in this case Swedish. All good so far.
But when the view calls Html.DropDownList() the selected languages' selected property changes to false. A couple of pictures might explain this better.
Before calling #Html.DropDownList("language", Model.LanguageSelectListItems)
Immediately after #Html.DropDownList("language", Model.LanguageSelectListItems)
You can see that the Selected property for the Swedish language has changed to false on the SelectListItem, and this is the resultant HTML :
<select name="language" id="language">
<option value="2">English</option>
<option value="3">Finnish</option>
<option value="4">Swedish</option>
</select>
Any ideas why this might be happening ?
Edit: LanguageSelectListItems is being populated and the selected language being set using this function (where languages is an enumerable of language) :
public static IEnumerable<SelectListItem> GetLanguageList(int selectedIndex)
{
var selectListItems = new List<SelectListItem>();
foreach (var language in languages)
{
selectListItems.Add(new SelectListItem() { Text = language.Name, Value = language.Id });
}
if (selectedIndex >= 0)
{
selectListItems[selectedIndex].Selected = true;
}
return selectedListItems;
}
Well if anyone else finds themselves in this strange situation, the solution to my problem was this.
In the controller action method before returning the view with the SelectList drop down, there was this line of code :
ViewBag.language = Model.Language;
This seemed to be interfering with the way the SelectList was being constructed in the view :
#Html.DropDownList("language", Model.LanguageSelectListItems)
After removing this line from the controller the SelectList started defaulting to the correct value. This fixed both Html.DropDownList and Html.DropDownListFor. I also discovered this in another area of the site where the behaviour was the same, but this time a ViewData[""] was being used.
So if you do run into this problem, check your local areas for any uses of ViewBag and ViewData that use the same name as the property you are trying to construct the drop down for.
On my view I am using a list as my model and each list item is of type model, so it looks like this:
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
and I am trying to loop through this list and add a specific property to a DropDownListFor:
#for (int i = 0; i < Model.Count(); i++)
{
Html.DropDownListFor(model => model.ElementAt(i).module, new SelectList(Model, Model.ElementAt(i).module));
}
But when I do this it doesn't render a dropdownmenu on my page.
Can someone help?
You can't render a dropdown list for a model because there is no way of representing the model in its entirety in a dropdown. What is ASP.NET supposed to render?
What you can do if you would like to select a model from a list is to run a LINQ Select query on the list, whereby you create an IEnumerable<SelectListItem> like this:
var selectList = Model
.Select(x => new SelectListItem
{
Name = x.module_name,
Value = x.module
});
I have tried to take the values from the screenshot that you posted. Apologies if I made an error. You get the idea...
What this code does is loop through the collection of your object type (Model.Select) and returns a collection of SelectListItem. If you are unfamiliar with LINQ you need to think of Select as a transformative function. It takes a collection, and for each element transforms it into something else and returns the result. Here, it takes each element of the Model collection and creates a SelectListItem. It then returns an IEnumerable<SelectListItem>.
To render the list on the page you do the following:
#Html.DropDownListFor(Model.MyValue, selectList)
...where Model.MyValue is the variable which receives the selected value (assuming that the value, model is a string, which it appears to be).
Hey,
I Have three IQueryable lists which i concat together into one list to be displayed in the dropdown box. But now I want to get the id of what the user selected since there are 3 lists to choose from. Thanks
Example:
IQueryable<Store> stores= _storeRepository.FindAll().OrderBy(c => c.Description);
var storeList = stores.ToSelectList("StoreId", "Description", viewModel.StoreId.ToString());
IQueryable<Product> products = _productRepository.FindAll().OrderBy(j => j.Name);
var productList = products.ToSelectList("ProductId", "Name", viewModel.ProductId.ToString());
var viewList = storeList.Concat(productList).ToList();
viewModel.Lookups = viewList; //display in dropdown
if you question was i have 3 lists and the user choose one how can i know which one he chosen
Answer :
you give all three the same name and the value will change depend on which one the user have chosen
if your question was i want to send the id value with the selected list
Answer :
the server doesn't have any info about your html attributes
just the name attribute which maps to the action method parameter name and the value which maps to the parameter value , you can't know the id value and other attributes in the server
Example :
<input type="text" name="Title" id="SomeValue"/>
Will Map To :
public ActionResult Index(string Title)
the server will not recive id="SomeValue"
Solution :
What you can do is place a hidden field under every item with the value you want
instead of this way, after concatenating do this
viewdata["viewList"] = storeList.Concat(productList).ToList();
and view display items in dropdown like this
<%= Html.DropDownList("viewlist_id", (List<SelectListItem>)ViewData["viewlist"])%>
now use a submit button (if want to post the data to same action else use actionlink with routvalues if redirecting to different action,I am using here submit button)
<input type="submit" name="submit" value="submit" />
and in your action you can retrieve the posted data
var dropdown_id = Request.Form["viewlist_id"];
this way you will get the id of selected drop down. thanks
So i figured out how to have the values of different lists combined into one dropdown list will still being able to access its actual value or ID without concat or union- the code is a lot if anyone is interested i will go ahead and take the time to properly post it. Other than that, thank you everyone for offer your advise and help. Thanks
So this is how i went about my problem. In my Controller File - in my Get method after the button click this is what i did:
resultSummaryViewModel.Value = value;
resultSummaryViewModel.ReportFrame = new FramedViewModel();
if(value !="")
{
string viewValue = value.Substring(0, value.IndexOf("|"));
string viewType = value.Substring(value.IndexOf("|") + 1);
resultSummaryViewModel.ReportFrame.SourceURL =
WebPathHelper.MapUrlFromRoot(
string.Format(
"Reporting/ResultSummary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}",
resultSummaryViewModel.BeginDate, resultSummaryViewModel.EndDate, viewValue,
viewType));
}
var viewData = new Dictionary<string, string>();
viewData.Add("Schools", "|allschools");
viewData.Add("Classes", "|allclasses");
This is also connected to my display page aspx.cs which contains the actual lists i use to populate.