Im kinda stuck, I have a drop down that I am trying to combine two fields from the same table into. Its kinda working, here is what I get:
The offending drop down list
As you can see, im pulling stuff I dont want into it, and im not pulling in my last name.
Here is my edit controller:
var DocList =
db.Doctors
.Select(s => new
{
Value = s.ID,
FirstN = s.FirstName,
SurN = s.Surname,
})
;
ViewBag.Doctor = new SelectList(DocList, "FirstN", "SurN", episode.Doctor.ID);
and here is my razor snippet:
#Html.DropDownList("docTest")
What do you guys think is going wrong here? Thanks in advance! :)
Looks like you may be needing to do something like this (it will give the dropdown the id of "docTest"):
#Html.DropDownList("docTest", (SelectList)ViewBag.DoctorOLD, "Place Holder Text", new { #class = "someClass" })
but you may need different functionality, I cannot tell from the amount of code supplied.You may also look into using #html.DropDownListFor if you need to bind the drop down value to a model property.
This SO post here does a great job of explaining html helper drop down list.
You are not binding the value to drop down list.Use below code to get the values
#Html.DropDownList("docTest",(IEnumerable<SelectListItem>)ViewBag.DoctorOLD)
Okay here is the solution im still pretty green at this so where I came unstuck was knowing the overloads. Let me try to explain (and correct me if im wrong)
Okay so we invoke our list. Now our first overload is the ieneumerable, this gets our bunch of stuff we want in our list. Next we want our value field, which is the column in your table that other tables use to link to it, in most cases its the ID column.
Next is the string. In my case its "FullName" and is basically made up of the FirstName and Surname from within my Doctors table.
Anyway if your dyslexic like me just look at the code below and pick it apart :)
The Controller:
ViewData["docFullDetails"] =
new SelectList((from s in db.Doctors
select new
{
FullName = (s.FirstName + s.Surname),
ID = s.ID
}),
"ID",
"FullName");
The View:
<div class="form-control">
#Html.DropDownList("docFullDetails")
#Html.ValidationMessageFor(model => model.Doctor)
</div>
In your controller you should populate your dropdown list like
ViewBag.Doctors = new SelectList(db.Doctors.Select(d => new { d.Id, FullName = d.FirstName + " " + d.LastName }),
"Id", "FullName");
And then in view create dropdown with razor
#Html.DropDownList("DoctorId", ViewBag.Doctors as SelectList, "Select doctor...", new { #class = "form-control" })
Your model for form that you are creating probably should have DoctorId property which you are binding from dropdown
#Html.DropDownListFor(m => m.DoctorId, ViewBag.Doctors as SelectList, "Select doctor...", new { #class = "form-control" })
Related
Been googling for a while, but I can't seem to get any closer.
I'm using MVC with an EF Database structure.
I want the dropdownlist items in the View to show up with different names than what they come up with.
Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name. Eventually, the selected field needs to be used in another lambda as the Byte that it was.
Edit
//view
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
#Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })
....
//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
orderby t.TYPE
select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);
....
Thanks in advance.
You can create a SelectListItem to display in your dropdownlist.
Example:
#Html.DropDownListFor(model => model.YearStartedToPay,
Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)
In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.
You need to make use of dropdownlist's Value property. Make your list a type of SelectListItem.
Assign Text= [Your Required Text] and Value = [Current Name]
I have a list created from a controller which is passed to a viewbag item:
List<SelectListItem> PTL = new List<SelectListItem>();
List<PT> PTL2 = db.PT.ToList();
foreach (var item in PTL2)
{
PTL.Add(new SelectListItem { Value = item.ID.ToString(), Text = item.Name });
}
ViewBag.PTL2 = PTL2;
Then, in the view, I tried the following from another question here:
#Html.DropDownList("test", new SelectListItem[]{
new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}}
, htmlAttributes: new { #class = "form-control" })
which worked fine, but, if I try to edit it to the following:
#Html.DropDownList("test", ViewBag.PTL2, htmlAttributes: new { #class = "form-control" })
I get various errors.
I have spent hours on this trying different combinations, different castings and more, but, I just don't seem to be making progress.
I have seen so many different errors - the most common one being '
There is no ViewData item of type IEnumerable<SelectListItem> that
has the key “test”'
However, I tried casting and changing the name as per different questions here, but, I just can't seem to get past this.
At this point, I am thinking of just making a manual HTML Drop Down list and a foreach loop for the content, but, this seems a waste.
Does anyone know what I have done wrong?
The second parameter must be a collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list. But, you are using ViewBag property in this case and the type of this is dynamic. So, you must cast it to the collection of the SelectListItem. Otherwise, you will get this error in MVC 4+:
Extension methods cannot be dynamically dispatched
So. as a result just change
ViewBag.PTL2
to
ViewBag.PTL2 as IEnumerable<SelectListItem>.
i hope it is not too late ,this is how i do it with .net core
in your controller ,use below code
public ActionResult ShowCalendar()
{
var programs = new Microsoft.AspNetCore.Mvc.Rendering.SelectList((new Programs().GetAll().ToList(), "ID", "Name")
ViewBag.AllItems = programs;
return View();
}
and in your cshtml file use the below
<select id="ItemID" class="form-control"
asp-items="ViewBag.AllItems">
<option disabled selected>--- #Localizer["PleaseSelect"] ---</option>
</select>
will do the job for you
I'm trying to develop a website using asp.net mvc 4 & EF6 where I'm using dropdownlist to assign datas to my required textboxes. So far I've managed to assign data to two textboxes where one holds the value of the selected item of dropdownlist & one holds the text given for the selected item. But I need to add another value from the selected item. My codes are below,
Controller
ViewBag.Clients = new SelectList(db.ClientInfoes, "age", "fullname"); //This is given
ViewBag.Clients = new SelectList(db.ClientInfoes, "id", "age", "fullname"); //I want something like this
View
#Html.DropDownList("Clients", "Select...")
// Textboxes are populated automatically by using jQuery
#Html.TextBoxFor(a => a.Fullname, new { id = "clientName", #readonly = "readonly" })
#Html.TextBoxFor(a => a.Age, new { id = "clientAge", #readonly = "readonly" })
How can I assign more than one value in the SelectList? Any way I can do that would be fine. Need this help badly. Thanks.
It looks like you want to show name and age both in the dropdown text, in that case you need to project the result coming from database :
var ClientInfoes = db.ClientInfoes
.Select(x=>
new {
id = x.id,
name = x.fullname+","+x.age
});
ViewBag.Clients = new SelectList(ClientInfoes, "id", "name");
While binding dropdown in MVC, I always get this error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country.
View
#Html.DropDownList("country", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Controller
List<Companyregister> coun = new List<Companyregister>();
coun = ds.getcountry();
List<SelectListItem> item8 = new List<SelectListItem>();
foreach( var c in coun )
{
item8.Add(new SelectListItem
{
Text = c.country,
Value = c.countryid.ToString()
});
}
ViewBag.countrydrop = item8;
return View();
I don't know how to resolve it.
If you were using DropDownListFor like this:
#Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)
where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.
Avoid this by simply initializing it in constructor, like this:
public MyModel()
{
MySelectList = new SelectList(new List<string>()); // empty list of anything...
}
This often happens in POST actions. Make sure you assign something before re-rendering the view.
In your action change ViewBag.countrydrop = item8 to ViewBag.country = item8;and in View write like this:
#Html.DropDownList("country",
(IEnumerable<SelectListItem>)ViewBag.country,
"Select country")
Actually when you write
#Html.DropDownList("country",
(IEnumerable)ViewBag.country,
"Select country")
or
Html.DropDownList("country","Select Country)
it looks in for IEnumerable<SelectListItem> in ViewBag with key country, you can also use this overload in this case:
#Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown
See Working DEMO Example
Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.
Always reinitialize your select list within a POST action.
For further explanation:
Persist SelectList in model on Post
try this
#Html.DropDownList("ddlcountry",(List<SelectListItem>)ViewBag.countrydrop,"Select country")
In Controller
ViewBag.countrydrop = ds.getcountry().Select(x => new SelectListItem { Text = x.country, Value = x.countryid.ToString() }).ToList();
Try This.
Controller:
List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");
I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me.
Solution for the similar problem
In my case, the error occurred because I had not initialized the select list in the controller like this:
viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();
As none of the existing answers made this clear to me, I post this. Perhaps it helps anybody.
your code is correct because in some cases it does not work, I also do not know where the error comes from but this can help you solve the problem, move the code in the head of the view like this:
index.cshtml:
#using expert.Models;
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
Manager db = new Manager();
ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE");
}
<div class="form-group">
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
<div class="col-md-10">
#Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { #class = "w3-select ", #required = "true" })
</div>
</div>
you can use this:
var list = new SelectList(countryList, "Id", "Name");
ViewBag.countries=list;
#Html.DropDownList("countries",ViewBag.countries as SelectList)
Replace "country" with "countrydrop" in your view like this...
#Html.DropDownList("countrydrop", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Could be like for ASP.NET MVC Framework
#Html.DropDownList("country", ViewBag.countrydrop as List<SelectListItem>,"Select country")
or ASP.NET Core MVC
<select class="class" id="country"
asp-items="#(new SelectLits(ViewBag.countrydrop,"Value","Text"))">
You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..
Happy Coding :)
Is it possible when using Html.TextBoxFor to override the name attribute?
I have tried with no success. I need to use TextBoxFor to get client side validation to work, however for reasons I won't go into I need the name of the textbox to be different from the generated one.
I have tried the following:
#Html.TextBoxFor(x => x.Data, new { name = Model.Key + "_Data", id = Model.Key + "_Data" })
Which works for ID but not name. Is this possible?
Update: Looking into the code for TextBoxFor. It doesn't look like there is an easy way. Hopefully someone can prove me wrong.
Rob, actually there is a much simpler way. Instead of name, use Name:
#Html.TextBoxFor(x => x.Data, new { Name = Model.Key + "_Data", id = Model.Key + "_Data" })
Are you asking this because you want to apply a prefix to the name? If so, you can do this by setting ViewData.TemplateInfo.HtmlFieldPrefix in your Controller.
I learnt a lot about this stuff from Brad Wilson's blog.
EditorFor has an overload where you can supply the name attribute as a parameter:
#Html.EditorFor(expression, null, name)
Try EditorFor. you can pass string as template name if you want to make sure textbox is rendered even if property type is not string. If property is string already, it does not need templatename explicitly to render textbox, so you can pass null. Note that it does not require id parameter explicitly, it will infer it from element name. And all the validation things are still active with EditorFor
#Html.EditorFor(x => x.Data, "string", Model.Key + "_Data")
It is called Microsoft GOTCHA...
Use the name in caps, like this
#Html.TextBoxFor(m => m.Reply.Answer, new { Name = "Whatyouwant" })
ben's answer got me what I was looking for except you need to wrap in in Html.Raw
#Html.Raw(Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData"))
a little bit "unpretty"=), try:
#Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData")
For me, it works! I hope that help!
#Html.EditorFor(model => model.Nome, new { htmlAttributes = new { #class = "form-control", #maxlength = "80", #id = "NomeFilter", #Name = "NomeFilter" } })
#Html.EditorFor(Model => Model.Something, "name", "name", new {#class = "form-control" })
Not sure which of those two string parameters in the middle do the work, but it worked only when I typed both of them.
For this example, I was disabling form fields based on permissions, but still showing them. I had a hidden field to send the value to the controller, but wanted a different field name in the EditorFor.
First param after model value represents the "name" property, second is the new name.
#Html.EditorFor(m => m.UserName, "name", "UserNameDisabled", new { htmlAttributes = new { #class = "form-control", #disabled = "disabled"} });
Results in:
<input class="form-control text-box single-line" disabled="disabled" id="UserNameDisabled" name="UserNameDisabled" type="text" value="someEnteredValue" />
Keep it simple, your already providing the ID you should simply be able to use the method "TextBox" instead of "TextBoxFor" and it will work fine client side and server side. In addition, although the accepted answer will work but will produce duplicate Name attributes on your tag if you inspect it using a browser. The below solution does not have that problem.
MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)
#Html.TextBox(Model.Key + "_Data", Model.Key, new { id = Model.Key + "_Data" }