Remove blank/empty entry at top of EnumDropDownListFor box - c#

I am rendering a drop down list box using my enums and I only have 3 options, but for some reason it is displaying four. The top and default option is simply blank/empty and I want this removed. I want the top/default value to be 'Option1'.
Enums:
public enum EventType
{
[Display(Name = "Option 1")]
Option1,
[Display(Name = "Option 2")]
Option2,
[Display(Name = "Option 3")]
Option3
}
View:
#Html.EnumDropDownListFor(model => model.EventType, null, new { #id = "eventType", #class = "form-control" })
Thanks for your help.

Your second parameter is the "Option Label" which is used to set the first item in the dropdown. From the documentation: "The text for a default empty item"
Use an overload that doesn't take in the option label:
#Html.EnumDropDownListFor(model => model.EventType, new { #id = "eventType", #class = "form-control" })
UPDATE
I just tried your code. When I do both:
#Html.EnumDropDownListFor(model => model.EventType, null, new { #id = "eventType", #class = "form-control" })
And
#Html.EnumDropDownListFor(model => model.EventType, new { #id = "eventType", #class = "form-control" })
I get:
The only time I get another option in the dropdown is when I pass in a string as the second parameter, such as "Select..."
Any chance you are doing something with javascript to add an item to the dropdown?

I also had the same problem.Solved this starting enum from 0 not 1 .
public enum EventType
{
[Display(Name = "Option 1")]
Option1,
[Display(Name = "Option 2")]
Option2,
[Display(Name = "Option 3")]
Option3
}
#Html.EnumDropDownListFor(model => model.EventType,
new {#id = "eventType", #class = "form-control" })

I spent some time getting the above to work and was unsuccessful.
I found an alternative way :
HTML:
#Html.DropDownList("types",
Helper.Gettypes(),
new { #class = "form-control", #title = "--- Choose ---" })
Code:
public static List<SelectListItem> Gettypes()
{
var enums = Enum.GetNames(typeof(WorkLogType)).ToList();
var selectLIst = enums.Select(x => new SelectListItem {Value = x, Text = x}).ToList();
return selectLIst;
}

Related

How to set default value "0" to text "Select" in DropDownList in MVC?

Below is the dropdownlist of Country. I want selected text "Select" which is working.
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
new { #class = "form-control" })
Now I want to set the value "0" for text "Select" which is by default selected. Currently the value for "Select" is blank as shown below.
How can I do this? The value "Select" is not in the data source. I have to access this selected value in JQuery.
I have tried with these two but none of those are working.
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { #class = "form-control", #selected = "0" })
And
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { #class = "form-control", #selected = "0" })
Below is the controller code for CountryName values
ViewBag.CountryName = dbLMS.CountryMasters.Select(c => new { c.CountryId, c.CountryName }).OrderBy(c => c.CountryName).ToList();
You can do as follows:
Option-1:
#{
var countrySelectList = new SelectList(ViewBag.CountryName, "CountryId", "CountryName");
List<SelectListItem> countrySelectListItems = countrySelectList.ToList();
countrySelectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "0", Selected = true }));
}
#Html.DropDownList("ddlCountryName", countrySelectListItems , new { #class = "form-control" })
Option-2:
In the controller method:
List<SelectListItem> selectListItems = dbLMS.CountryMasters.Select(a => new SelectListItem()
{
Text = a.CountryName,
Value = a.CountryId
}).ToList();
selectListItems.Insert(0, new SelectListItem(){Text = "Selet Country", Value = "0", Selected = true});
ViewBag.CountrySelectList = selectListItems;
Then in the view:
#Html.DropDownList("ddlCountryName", (List<SelectListItem>)ViewBag.CountrySelectList, new { #class = "form-control" })
new SelectList(ViewBag.CountryName, "CountryId", "CountryName", //Default value)
You dont really need a value for Select. For the model, keep the Required validation attribute.
This will ensure the value is selected. This way you dont have to check in the backend.

How to set selected item in dropdownlist using LINQ?

Currently my code is selecting the first item in the list. I want it to select the item which matches the MakeModelTypeCode.
E.G.
The selected item in the dropdownlist should be where this code
vehicleViewModel.VehicleDTO.VehicleDetails.MakeModelTypeCode
= MakeModelTypeCode from x
Here is the relevant code from the Business Logic class:
vehicleViewModel.AvailableMakeModels = GetAllMakeModelTypesForClient(selectedClientId);
vehicleViewModel.AvailableMakeModels = vehicleViewModel.AvailableMakeModels.GroupBy(x => x.ModelDescription).Select(x => x.First()).Distinct().ToList();
var vehicleMakeList = vehicleViewModel.AvailableMakeModels
.Select(s =>
new SelectListItem
{
Selected = true,
Text = s.MakeDescription,
Value = s.MakeModelTypeCode
});
Here is the relevant code from the .cshtml:
<div class="col-sm-6">
#Html.LabelFor(m => m.VehicleDTO.VehicleDetails.MakeDescription)
#Html.DropDownListFor(x => x.SelectedvendorText, new SelectList(Model.AvailableMakesSelectList, "Value", "Text", "Make"), new { #class = "form-control uppercase", #id = "ddlAvailableMakes", name = "ddlAvailableMakes", #onchange = "FillModels()" })
#Html.ValidationMessageFor(m => m.SelectedMake, "", new { #class = "text-danger" })
</div>
Here is the code from the Controller:
[Route("Edit-{id}")]
[Authorize]
public ActionResult Edit(string id)
{
VehicleViewModel vehicleViewModel = new VehicleViewModel();
selectedClientId = HelperMethods.GetClientId();
vehicleViewModel.VehicleDTO = this.vehicleBusinessLogic.GetClientVehicleDTO(id, this.selectedClientId);
vehicleViewModel = this.vehicleBusinessLogic.SetUpUpdateVehicle(vehicleViewModel, selectedClientId);
vehicleViewModel.VehicleDTO.VehicleDetails.ClientID = this.selectedClientId;
return View(vehicleViewModel);
}
I have tried a few different ways but can't get any to work. I can get just the item I want returned but not all the items + the selected item.
I was thinking I could do a nested Where clause inside the Select but that doesn't seem to work, but maybe my syntax was in-correct.
How about
MakeModelTypeCode toBeSelected;
var vehicleMakeList = vehicleViewModel.AvailableMakeModels
.Select(s =>
new SelectListItem
{
Selected = s.MakeModelTypeCode == toBeSelected,
Text = s.MakeDescription,
Value = s.MakeModelTypeCode
});
Changing the .cshtml to the below resolved the issue.
The only change was to replace x => x.SelectedvendorText with m => m.VehicleDTO.VehicleDetails.MakeModelTypeCode
<div class="col-sm-6">
#Html.LabelFor(m => m.VehicleDTO.VehicleDetails.MakeDescription)
#Html.DropDownListFor(m => m.VehicleDTO.VehicleDetails.MakeModelTypeCode, new SelectList(Model.AvailableMakesSelectList, "Value", "Text", "Make"), new { #class = "form-control uppercase", #id = "ddlAvailableMakes", name = "ddlAvailableMakes", #onchange = "FillModels()" })
#Html.ValidationMessageFor(m => m.SelectedMake, "", new { #class = "text-danger" })
</div>

How to keep the id from the selectlist when using multiple columns in the textfield

I am trying to show multiple columns from my database in a dropdownlist using a SelectList
public ActionResult Create()
{
var times = db.Show_Courses
.Select(x =>
new {
id = x.show_course_id,
times = x.show_course_before + "," + x.show_course_after
});
ViewBag.course_id = new SelectList(times, "id", "times");
return View();
}
It shows up properly in the view but in the database the value of the id is 0
This was my code before i wanted to show two columns in the textfield of the selectlist
public ActionResult Create()
{
ViewBag.course_id = new SelectList(db.Show_Courses, "show_course_id", "show_course_time_before");
return View();
}
And here is my code in the view
<div class="form-group">
#Html.LabelFor(model => model.course_show_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("course show id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.course_show_id, "", new { #class = "text-danger" })
</div>
</div>
So my question is how can I display 2 values in the Textfield of the Selectlist without the id becoming 0?
You could generate SelectList manually.
For example,
ViewBag.course_id = db.Show_Courses
.Select(x => new SelectListItem {
Text = x.show_course_before + "," + x.show_course_after,
Value = x.show_course_id.ToString() })
.ToList();
I personally like to use strongly type model. You can read more here
Your code seems to be fine, you need to map the dropdown to according value from model: show_course_id - from what I see, so please update your dropdown to:
#Html.DropDownList("show_course_id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })

Display placeholder text from Language resource file

I have a text area to show the description and my model for the same looks like
[Display(Name = "CopyrightHolder_AdditionalInfo_Label", ResourceType = typeof(Resource))]
public string AdditionalInfo { get; set; }
And in Razor i am using the form like this
<div class="form-group">
#Html.LabelFor(model => model.AdditionalInfo)
#Html.TextAreaFor(model => model.AdditionalInfo, new { #class = "form-control", #rows = "5", #placeholder = "i wnat to load from resource file this text", #maxlength = "545" })
#Html.ValidationMessageFor(model => model.AdditionalInfo)
</div>
I am also planning to show a placeholder on this text area which should load from resource file
Is there any way to do the same ?
you can add it like below:
#Html.TextAreaFor(
model => model.AdditionalInfo,
new {
#class = "form-control",
#rows = "5",
#placeholder = #Resources.Strings.YourKeyString,
#maxlength = "545"
}
)

DropDownList not selected in Edit page

I Created Controller with "MVC 5 Controller with views, using Entity Framework" and modify "DropDownList" code in "Edit" view to
#Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.prdepno, new { #class = "form-control" })
in Controller use ViewBag
personal personal = db.personals.Find(id);
ViewBag.prdepno = new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);
no error ,but dropdownlist not selected
I lookup from Adding a css class to select using #Html.DropDownList()
and other question try to do that, but It not work (for me)
I don't know to do
(sorry, in my communication.)
I think you need to change the name of ViewBag Object
personal personal = db.personals.Find(id);
ViewBag.DwPrdeps= new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);
after that use ViewBag.DwPrdeps in your view
#Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.DwPrdeps, new { #class = "form-control" })
Try With this code It's Work properly
Code Generate/ Model
public class CityList
{
public string city { get; set; }
}
public static IEnumerable<SelectListItem> GetCity()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "Dhaka", Value = "dhk" },
new SelectListItem{Text = "Chittagong", Value = "CTG" }
};
return items;
}
For Create
ViewBag.city = new SelectList(GetCity(), "Text", "Value");
#Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { #class = "form-control select2", required = "required" })
For edit
ViewBag.city = new SelectList(GetCity(), "Text", "Value",model.city);
#Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { #class = "form-control select2", required = "required" })
You Can Try This it's work fine.

Categories