Knockout doesn't bind selectedValue in a select properly - c#

It seems impossible and I have tried a few different ways to create a select list and bind a value to it.
Firstly, and more desirably, I want to do it with Razor:
#Html.DropDownList("SelectedTemplate", Model.Templates, new { #data_bind = "value: Template()" })
The options are just an array of strings. When I bind with Razor then it's a List of SelectListItem objects with Text and Value equal to the same string.
So it renders like this:
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
When I bind via Knockout then the Templates is an array of strings:
var Templates ='["A", "B", "C"]';
which I generate in the cshtml file:
var Templates ='#Html.Raw(Json.Encode(Model.Templates.Select(x=> x.Value)))';
Both create the same markup in HTML. This renders the select list correctly. Template() prints out the correct value, for example "B". However, the drop down doesn't pick the option that is equal to Template(). I also tried:
<select name="SelectedTemplate" data-bind="value: Template(), options: JSON.parse(Templates)"></select>
Same problem here. And I tried all kinds of variations:
#Html.DropDownListFor(m => m.SelectedTemplate, Model.Templates, new { #class = "form-control layoutTemplateSelector", #data_bind = "value: Template(), options: JSON.parse(Templates)" })
#Html.DropDownListFor(m => m.SelectedTemplate, Model.Templates, new { #class = "form-control layoutTemplateSelector", #data_bind = "value: Template()" })
#Html.DropDownList("SelectedTemplate", Model.Templates, new { #data_bind = "value: Template(), options: JSON.parse(Templates)" })
Ideally, I want to use DropDownListFor because on post back I want m.SelectedTemplate to be processed.
The postback works well so far for DropDownListFor, but on load it doesn't show the data-bind: value:Template(), which definitely contains the correct value.
I also tried your idea to use observable array with no success:
self.SelectedContent({
Template: ko.observable(content.Template()),
TemplateList: ko.observableArray(JSON.parse(Templates))
});
#Html.DropDownListFor(m => m.Form.Template, Model.Templates, new {#data_bind = "value: Template(), options: TemplateList()" })
Any ideas what could be wrong here? I'm using Knockout 2.3 and MC.
UPDATE
I found the error.
The value returned from the database contained a space: "A "
whereas the values binding the to the drop down didn't have that space.
This caused all the errors.
As far as I can see the simplest of implementations works well now:
#Html.DropDownList("SelectedTemplate", Model.Templates, new { #data_bind = "value: Template()" })
Even though it was entirely my mistake, I hope it helps someone in the future. The error wasn't immediately apparent

Related

How to add and empty select list with Html.DropDownList

I am trying to add a drop down select element to my .net page, but I need it to be black so I can populat it with a json list I have with jQuery. Right now, my view has this:
#Html.DropDownList("Language", new SelectList(" "), "name = 'Laguange'", new { #class = "Language-List field form-group form-control" })
This 'works', but it seems to be confusing some stuff when I try to submit the form it is in. The value I select from it is never seen by the model, as it keeps triggering my [Required] validation helper.
Does anyone know How to add this without the new SelectList(" ") attribute?
I would suggest it's because youre using the name attribute in the wrong place.
Try this:
#Html.DropDownList("Language", new SelectList(" "), new {Name="Language", #class = "Language-List field form-group form-control" })
Notice the capital Name
Although as they are the same, you can just leave it out:
#Html.DropDownList("Language", new SelectList(" "), new {#class = "Language-List field form-group form-control" })

MVC5 DropdlwonList: Set individual column length

I have a dropdown list that populates with two fields. Old_ItemID and ItemDescription. The user needs to see both of these fields in the dropdown.
Problem is that is messy. Originally it puts both fields next to each other without any spacing. It looks messy and is hard on the eyes. As you can see from the code below, I added some spacing. And that is much better.
The problem now is that it's not aligned because each Old_ItemID is a different length and depending on how many characters the Old_ItemID is, it pushed the ItemDescription left or right. And so it looks unorganized.
Is there a way to justify these columns in a tab setting, or somehow get the alignment correct?
Controller Code
List<SelectListItem> SuppliesList = db.ICS_Supplies.Where(s => s.InvType == "G").Select(x => new SelectListItem { Value = x.Supplies_ID.ToString(), Text = x.Old_ItemID + "\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0" + " | " + " " + " Description: " + x.ItemDescription, Selected = false }).DistinctBy(p => p.Text).OrderBy(p => p.Text).ToList();
ViewBag.SuppliesList = new SelectList(SuppliesList, "Value", "Text");
View Code
<div class="form-group">
#Html.Label("Supplies Requested:", new { #class = "form-control" })
#Html.DropDownList("SuppliesList", null, "Select", new { #class = "form-control", #onchange = "supplychange()" })
</div>
Note: I did a bit of research before asking this question, which is where I found how to add the spaces. But I can't seem to find a resource to show how to align with proper spacing so that it looks professional and not sloppy. Should be a common request, I would imagine?

Select the Html.DropdownFor

<div class="input-group" style="margin-bottom:30px;">
<span class="input-group-addon">
Brand
</span>
#Html.DropDownListFor(x => x.BrandMod.Id, c,"- Select Brand - ", new { #class = "form-control" ,id="brandid" })
</div>
"This is My Code for Drop Down and I want to select the selected item. I am trying this"
$("#brandid").change(function (rupp) {
var a = $(this).select("option:selected").val();
});
"I am Unable to Load the Selected item."
This doesn't do what you're thinking:
$(this).select("option:selected").val()
In fact, it's probably either silently failing entirely or producing an error. But no matter. What you're trying to do is get the value from this (which is a <select> in your case). That can be done simply with:
$(this).val()
You don't need Specification for getting value in jquery. You have already change event for this
$("#brandid").change(function (rupp) {
var a = $(this).val();
});
or
var a = $("#brandid").val();

add extra option to an already populated dropdownlist in mvc

I have an html dropdownlistfor which is being populated from my database, this I was able to do successfully but the issue I am having now is including an additional option not available in the database as an option that can also be selected.it is actually a list of items but I want a give an option ALL which when selected means the user is selecting all the items displayed in the database, my major issue is how to include the ALL option. I have searched and read similar questions but they are not what am trying to achieve. thanks for your help. here is my code
in my controller I have this:
var load = from bh in db.IV_001_ITEM
select bh;
ViewBag.selection = new SelectList(load.ToList(), "item_code", "item_name", glay.vwstring2);
in my view I have this:
<div class="col-sm-2">
#Html.DropDownListFor(m => m.vwstring2, ViewBag.selection as SelectList, "Select", new { #class = "form-control", required = "required", id = "selectc" } )
</div>
You can use the Add method to explicitly add an extra option (SelectListItem)
List<SelectListItem> optionList = db.IV_001_ITEM
.Select(x=>new SelectListItem { Value=x.item.code,
Text=x.itemName}).ToList();
// Now add the item you want
optionList.Add(new SelectListItem { Value="Foo",Text="Bar"});
//use this now
ViewBag.Items = optionList;
// You can set the selected item on your view model property
myViewModelObject.vwstring2 = glay.vwstring2; //For the selected item
return View(myViewModelObject);
In your view,
#Html.DropDownListFor(m => m.vwstring2, ViewBag.Items as List<SelectListItem>,
"Select", new { #class = "form-control"})

Html DropDownListFor asp.net C#

Could some please convert the following code to a standard html tag? Something like <select id="selectDomain" name="selectDomain">, IF it converts to a select tag.
#Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>(), "", new { id = "selectDomain", name = "selectDomain"})
If I understand correctly, doesn't x => x.domain mean id="domain" name="domain"? Is this code overwriting the name and id to selectDomain?
Finally, if it isn't convertible to an html tag, I want to add a class to the given code. I tried adding it inside the new{} like new{id="selectDomain", name="selectDomain", class="form-control"} section but it gave me error saying expected }
You understand correctly if you write:
#Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>())
Razor will produce:
<select id="domain" name="domain"> </select>
It's better to use ViewModel and create property selectDomain in it and then:
#Html.DropDownListFor(x => x.selectDomain, Enumerable.Empty<SelectListItem>(), new { #class="form-control" })
Will make html that you want.
But if you don't want to do it you can use Html.DropDownList helper like this:
#Html.DropDownList("selectDomain",Enumerable.Empty<SelectListItem>(), new { #class="form-control" })
note escaped class with # symbol.
You can specify "name" with uppercase first letter (works in MVC5)
#Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>(), "", new { id = "selectDomain", Name = "selectDomain"})
result:
<select name="selectDomain" id="selectDomain">

Categories