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" })
Related
I don't know how to sum up what I'm trying to do in the title properly! Basically I have created a controller with EF6 and one foreign key of the Client table is MJTopicsID which links to the MJTopics table, a table of 26 topics. In the add and edit view I want the MJTopicsID to be a drop down menu displaying all the topics available however when you select it and click to add or edit an entry it adds it to the Client table as the MJTopicsID foreign key number? How do I go about this so I can apply it to all of my views.
This is the dropdown menu I created in the edit view however it just shows numbers 1-26 and if I change it to the topics variable it doesn't know it as obviously its not in the open model, thanks!
<div class="form-group">
#Html.LabelFor(model => model.MJTopicsID, "MJTopicsID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MJTopicsID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MJTopicsID, "", new { #class = "text-danger" })
</div>
</div>
If I understood correctly then you want to display some readable value and save some db specific value like foreign key Id in this case.
In the view for helper method "DropDownList" you can give second parameter of type IEnumerable type as a list of your options like this:
View:
#Html.DropDownList("MJTopicsID",
(List<SelectListItem>)#ViewBag.MJTopics,
htmlAttributes: new { #class = "form-control" })
Action:
public ActionResult Index()
{
ViewBag.MJTopics = new List<SelectListItem>() {
new SelectListItem(){Text = "Topic1", Value ="1" },
new SelectListItem(){Text = "Topic2", Value ="2" }
};
return View();
}
SelectListItem has two properties which you can map with your models.
Also you can use your model with "Text" as value to display and "value" as value to use.
Let "topics" is your list model for topics
then you can write it as
topics.Select(
x=> new SelectListItem()
{
Text = x.Id,
value =x.Desc
})
This is the one way of doing it.
I hope it will solve your problem.
I wanted to add an answer if anyone is new to EF6 and is trying to do the same thing.
In the controller for the actionresult you are trying to do this for, so in my case create it will create a viewbag variable this was mine:
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "ID");
I changed it to:
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "topicalTF");
The topicalTF is the variable for the topics available and this showed all the topics but would save it as the ID, hope this helps!
<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();
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"})
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
I am using below code to create a drop down
Controller
ViewBag.Id= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")
View
#Html.DropDownList("Id", null, htmlAttributes: new { #class = "form-control" })
My question is how can I Modify SelectList to add a blank item so that there is a blank item automatically added for DropDownList.
Thanks.
Use one of the overloads that accepts an optionLabel
#Html.DropDownListFor(m => m.ID, (SelectList)ViewBag.MyList, "Please select", new { #class = "form-control" })
or if you do not want to use the strongly typed methods
#Html.DropDownList("ID", (SelectList)ViewBag.MyList, "Please select", new { #class = "form-control" })
Which will add the first option with the text specified in the 3rd parameter and with a null value
<option value="">Please Select</option>
You can use this overload:
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes);
where optionLabel is the text for a default empty item.
In my project, these work:
Controller
ViewBag.TagHfoFlagId= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")
View
#Html.DropDownList("TagHfoFlagId", null,"--Select Name--", htmlAttributes: new { #id = "tags" })
The accepted answer does work, but it will show the default (null) value in the view's drop down list even if you already selected one before. If you want the already selected value to show itself in the drop down list once you render back the view, use this instead :
Controller
ViewBag.Fk_Id_Parent_Table = new SelectList(db.Parent_Table, "Id", "Name", Child_Table.Fk_Id_Parent_Table);
return View(ChildTable);
View
#Html.DropDownList(
"Fk_Id_Parent_Table",
null,
"Not Assigned",
htmlAttributes: new { #class = "form-control" }
)