I have one of a method as following in my controller
Code
var companies = ...
List<CompanyModel> listOfCompanies = new List<CompanyModel>();
foreach (var item in companies)
{
listOfCompanies.Add(new CompanyModel(item.CompanyId, item.CompanyName));
}
ViewBag.Company = listOfCompanies;
View page
#Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Company, "id", "name"), "Select company", new { #class = "form-control" })
this is working fine , I'm trying trying to use session instead of viewbag here.
So for that I did
var companies = ...
List<CompanyModel> listOfCompanies = new List<CompanyModel>();
foreach (var item in companies)
{
listOfCompanies.Add(new CompanyModel(item.CompanyId, item.CompanyName));
}
Session["CompanyData"] = listOfCompanies;
View page
#Html.DropDownListFor(m => m.Company, new SelectList(Model.Company, "id", "name", Session["CompanyData"]), "Select company", new { #class = "form-control" })
but this is not working properly, whats the path to achieve this
Have you tried simply replacing ViewBag with Session?
#Html.DropDownListFor(m => m.Company, new SelectList((List<CompanyModel>)Session["CompanyData"], "id", "name"), "Select company", new { #class = "form-control" })
Related
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.
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>
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" } })
Using first method I'm setting default subjects in listbox and using second I'm retrieving only these who was selected.
public void SubjectsList()
{
ViewBag.Subjects =
new SelectList(new[] { "Math", "Physic", "English" }
.Select(x => new { value = x, text = x }),
"Value", "Text");
}
public void SubjectsFromDb(int id)
{
var students = _db.Subjects.AsEnumerable().Where(x => x.StudentId == id).Select(q => new SelectListItem
{
Value = q.Name,
Text = q.Name,
}).ToList();
ViewBag.Subjects = students;
}
How can I do that in Listbox was all Subject but selected were only these which is in db?
Here's my listbox
<div class="form-group">
#Html.LabelFor(model => model.Subject, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.Subject,
new MultiSelectList((IEnumerable<SelectListItem>)ViewBag.Subjects, "Value", "Text"),
new { style = "display:block;" })
#Html.ValidationMessageFor(model => model.Subject)
</div>
</div>
Your model property Subject needs to be public IEnumerable<string> Subject { get; set; } although I would suggest it be renamed to Subjects - plural) and you rename the ViewBag property
The in the GET method, assign the existing subjects to the model
var model = yourModel()
{
Subjects = _db.Subjects.Where(x => x.StudentId == id).Select(q => q.Name);
};
ViewBag.SubjectList = new SelectList(new[] { "Math", "Physic", "English" });
return View(model);
Then in the view its
#Html.ListBoxFor(m => m.Subjects, (SelectList)ViewBag.SubjectList)
Side notes:
There is no need for the extra overhead of creating anonymous
objects to generate the SelectList - you can delete .Select(x => new { value = x, text = x }), "Value", "Text")
Since its already a SelectList, there is no need for the extra
overhead of creating another duplicate SelectList in the
ListBoxFor() method
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.