How to bind value to dropdownlist in asp.net mvc? - c#

I have several textboxes and one dropdownlist like:
for (int i = 0; i < count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #id = "ddlProjectvalue" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", #class = "sunhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", #class = "monhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", #class = "tuehrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", #class = "wedhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", #class = "thurhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", #class = "frihrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", #class = "sathrs" })
</td>
</tr>
</td>
}
and I want to bind data from database to all the fields , every thing is displaying data perfectly, but dropdown list for proj_id is not showing text even though i am passing value to dropdownlist. i am passing like :
public int GetTimsheetData(int empid, TimesheetModel TimesheetModel)
{
// GetimeSheet all the rows according employee name
var emps = (from n in db.TIMESHEETs
where n.RES_ID == empid
select n).ToList();
int count = emps.Count();
HttpContext.Current.Session["count"] = count;
try
{
List<TimesheetModel> emptyList = new List<TimesheetModel>();
TimesheetModel.GetTimeSheetDetails = emptyList; //taking Empty List and bind to GetTimesheetDetails for Add items into it.
//if Employee Name has more than one record.
if (emps.Count() > 0)
{
foreach (var timeSheet in emps)
{
TimesheetModel item = new TimesheetModel();
item.WEEK_CAL_ID = timeSheet.WEEK_CAL_ID;
item.PROJ_ID = timeSheet.PROJ_ID;
item.SUN_HRS = timeSheet.SUN_HRS;
item.MON_HRS = timeSheet.MON_HRS;
item.TUE_HRS = timeSheet.TUE_HRS;
item.WED_HRS = timeSheet.WED_HRS;
item.THU_HRS = timeSheet.THU_HRS;
item.FRI_HRS = timeSheet.FRI_HRS;
item.SAT_HRS = timeSheet.SAT_HRS;
TimesheetModel.GetTimeSheetDetails.Add(item);
}
}
}
catch (Exception ex)
{
throw ex;
}
return count;
}
and returning to controller like :
public ActionResult GetEmployeeDetails(int empId, string btn, TimesheetModel timesheetModel)
{
Employer_BL employerBL = new Employer_BL();
ViewBag.ProjectList = timesheetModel.getProjects;
//If GetTimesheetData returns morethan one record
if (employerBL.GetTimsheetData(empId, timesheetModel) >= 0)
{
timesheetModel.EMP_ID = empId;
//passes model data to View
return View("Timesheet", timesheetModel);
}
TimesheetModel model = new TimesheetModel();
model.EMP_ID = empId;
return View("Timesheet", model);
}
Where am I doing wrong, dropdownlist showing initial index instead of showing text of passing values. Please help me anyone.
in Separate Class I have written like below to get project names:
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}

It depends on the ViewBag.ProjectList which I cannot found on your source code. You could populate it with an object of type IEnumerable<SelectListItem> with one of the item Selected properties set to true.
public IEnumerable<SelectListItem> GetList()
{
return (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() }).ToList();
}
on your controller
ViewBag.ProjectList = GetList();
on your view
#{
var projectList =
new SelectList(ViewBag.ProjectList, "Value", "Text", Model.GetTimeSheetDetails[i].PROJ_ID.ToString())
}
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, projectList, "-- Choose a Project --")

You can try like this method:
[NonAction]
private IEnumerable<SelectListItem> GetData()
{
return new List<SelectListItem>()
{
new SelectListItem(){ Text="--Select--", Value="0"},
new SelectListItem(){ Text="A", Value="1"},
new SelectListItem(){ Text="B", Value="2"},
new SelectListItem(){ Text="C", Value="3"},
};
}
Call this function in Action Method
public ActionResult Create()
{
ViewData["categories"] = GetData();
return View();
}
On your html page:
<%= Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewData["categories"])%>

You can use viewbag . in your controller you can read your data from the database :
public ActionResult Create()
{
ViewBag.ClassName = new SelectList(objclassrep.GetClasslist(), "Id", "ClassName");
}
And in your view model you can read the data from controller like this :
<div class="editor-label">
#Html.LabelFor(model => model.ClassId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ClassId, (SelectList)ViewBag.ClassName);
#Html.ValidationMessageFor(model => model.ClassId)
</div>
This code automatically binds ids of your data to DDL Here is class id.
This is th getClassList function :
public List<Class> GetClasslist()
{
return _dbcontext.Classes.ToList();
}

Related

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>

Html.DropDownList doesn't display SelectList selected value

I've read a bunch of questions about the subject but haven't managed to find a solution to this specific problem.
Controller
public ActionResult Index() {
string categorie = "--Tout--";
string souscategorie = "--Tout--";
if (Session["Categorie"] != null) {
categorie = Session["Categorie"].ToString();
}
if (Session["SousCategorie"] != null) {
souscategorie = Session["SousCategorie"].ToString();
}
SelectList cats = new SelectList(GetCategories(), categorie);
SelectList sCats = new SelectList(GetSousCategories(), souscategorie);
ViewBag.Categories = cats;
ViewBag.SousCategories = sCats;
using(DAL.WebShopEntities entities = new WebShopEntities()) {
return View(entities.Article.ToList());
}
}
View
#Html.Label("Catégories")
#Html.DropDownList("Categories", (SelectList)ViewBag.Categories, new { #class = "form-control dropdownlist" })
<br />
#Html.Label("Sous-Catégories")
#Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategories, new { #class = "form-control dropdownlist" })
When debugging the view I can see clearly that the option stocked in the session is sent to the View. But it displays the index 0 when checking in the browser. This has me bugging because the SelectList behaves normally, I think the problem lays with the DropDown but what could be the problem?
Can you try to change your Viewbag property name and try again?
try Categories => CategoriesList and
SousCategories=> SousCategoriesList
public ActionResult Index() {
string categorie = "--Tout--";
string souscategorie = "--Tout--";
if (Session["Categorie"] != null) {
categorie = Session["Categorie"].ToString();
}
if (Session["SousCategorie"] != null) {
souscategorie = Session["SousCategorie"].ToString();
}
SelectList cats = new SelectList(GetCategories(), categorie);
SelectList sCats = new SelectList(GetSousCategories(), souscategorie);
ViewBag.CategoriesList = cats;
ViewBag.SousCategoriesList = sCats;
using(DAL.WebShopEntities entities = new WebShopEntities()) {
return View(entities.Article.ToList());
}
}
#Html.Label("Catégories")
#Html.DropDownList("Categories", (SelectList)ViewBag.CategoriesList, new { #class = "form-control dropdownlist" })
<br />
#Html.Label("Sous-Catégories")
#Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategoriesList, new { #class = "form-control dropdownlist" })

Retrieve all item in listbox and select only those which is in db

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

How do I pass a list to a controller from an Html.RadioButtonFor?

So basically I Have a view that has a Create New button and then a list of items, on the list of items I want to have a radiobutton that will allow the user to select it and carry over the details of the item to the Create New page when they Click on Create New
This is what I have on my view currently:
<tbody>
#for (int i = 0; i < Model.newExpenseFOPList.Count; i++)
{
<tr>
<td>#Html.TextBoxFor(m => m.newExpenseFOPList[#i].Category, new {style="width:100px; border-style: none;", #readonly = "readonly", onfocus="this.blur()", #maxlength = "60"})</td>
<td>#Html.TextBoxFor(m => m.newExpenseFOPList[#i].SubCategory, new {style="width:150px; border-style: none;", #readonly = "readonly", onfocus="this.blur()", #maxlength = "60"})</td>
<td>#Html.TextBoxFor(m => m.newExpenseFOPList[#i].CreditFund, new {style="width:45px; border-style: none;", #readonly = "readonly", onfocus="this.blur()", #maxlength = "8"})
#Html.TextBoxFor(m => m.newExpenseFOPList[#i].CreditORGN, new {style="width:45px; border-style: none;", #readonly = "readonly", onfocus="this.blur()", #maxlength = "8"})
#Html.TextBoxFor(m => m.newExpenseFOPList[#i].CreditProgram, new {style="width:45px; border-style: none;", #readonly = "readonly", onfocus="this.blur()", #maxlength = "5"})</td>
<td>#Html.TextBoxFor(m => m.newExpenseFOPList[#i].Amount, new { style="width:70px; border-style: none;", #maxlength = "50", #onkeypress="return isNumber(event)"})</td>
<td>#Html.RadioButtonFor(model => model.newExpenseFOPList[#i].CopyRadioButton, "CopyRadioButton", new { #Name="group1", #Value="copy"}) </td>
</tr>
}
</tbody>
And this is the controller tied to this view:
[HttpPost]
public ActionResult Expense(NewExpenseViewModel newExpenseViewModel, string submitAction, EditExpenseViewModel editExpenseViewModel)
{
//declare a variable of type list of ExpenseDistModel and fetch the SP getExpenseList values into it
List<ExpenseDistModel> expenseModelList = DataAccess.getExpenseList();
//instantiate the viewModel along with the values previously fetched by expenseModel
editExpenseViewModel = new EditExpenseViewModel(expenseModelList);
//Check Category is not already in the table or that the field is not empty
for (int i = 0; i < newExpenseViewModel.newExpenseFOPList.Count; i++)
{
if (newExpenseViewModel.selectedExpenseCategory == newExpenseViewModel.newExpenseFOPList[i].Category && newExpenseViewModel.selectedExpenseSubCategory == newExpenseViewModel.newExpenseFOPList[i].SubCategory || newExpenseViewModel.newExpenseFOPList[i].Category == null)
{
ViewBag.Message1 = "Category already exists or the field is empty.";
//invoke SP to populate table with Expense info
List<ExpenseDistModel> newExpenseModelList = DataAccess.getExpenseList();
//invoke SP to populate Category Dropdown in Create New Expense
List<CategoryModel> newCategoryList = DataAccess.getCategory();
//invoke SP to populate SubCategory Dropdown in Create New Expense
// List<SubCategoryModel> newExpenseSubCategoryList = DataAccess.getSubCategory();
List<SubCategoryModel> newExpenseSubCategoryList = new List<SubCategoryModel>();
//instantiate the newExpenseViewModel along with the values previously fetched by expenseDistModel
newExpenseViewModel = new NewExpenseViewModel(newExpenseModelList, newCategoryList, newExpenseSubCategoryList);
//return the viewModel
return View("CreateNewExpense", newExpenseViewModel);
}
}
return RedirectToAction("EditExpense", new
{
newExpenseCategory = newExpenseViewModel.selectedExpenseCategory,
newExpenseSubCategory = newExpenseViewModel.selectedExpenseSubCategory,
expenseCreditFund = newExpenseViewModel.newExpenseCreditFund,
expenseCreditORGN = newExpenseViewModel.newExpenseCreditORGN,
expenseCreditProgram = newExpenseViewModel.newExpenseCreditProgram,
submitAction = submitAction,
modifiedby = "test"
});
}
when I hover over newExpenseViewModel I see all the values but the radiobutton, that's null - any ideas?
UPDATE: I fixed my issue by passing the viewmodel instead of the list itself to the radiobutton - now I need to initialize it to "Unchecked"
<td>#Html.RadioButtonFor(model => model.CopyRadioButton,#i, new{#checked = false})</td>

How can I remove the double quotes after sending data to view with ViewBag?

I have many to many relationship in edit page how can i show selected items selected in a Dropdown multi select
here is my code:
// GET: Project/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var edata = db.Projects.Find(id);
//check if data
if (edata == null)
return HttpNotFound();
//IEnumerable<SelectListItem> items = db.Provinces.Select(c => new SelectListItem { Value = c.ID.ToString(), Text = c.Name });
//ViewBag.ProvinceId = items;
//---Get all provice-----
var Prov = from c in db.Provinces select c;
//------get province ids---------------
var prov_id = from o in db.ProRel where o.ProjectId == id select o.ProvinceIds;
List<int> mid_list = new List<int>();
foreach (var p_ids in prov_id)
{
mid_list.Add(p_ids);
}
var option_vals = "";
var selected = string.Empty;
foreach (var p_itmes in Prov)
{
if (mid_list.Contains(p_itmes.ID))
{
selected = "selected='selected'";
}
else
{
selected = "";
}
option_vals += "<option "+selected+" value="+p_itmes.ID+">"+p_itmes.Name+"</option>";
}
string test = option_vals.ToString();
string test2 = test.Replace("\"", "");
ViewBag.options = test2;
return View(edata);
}
in my edit view my code:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
<select name="prov" id="prov">
#ViewBag.options
</select>
</div>
</div>
it displays the option values with double quotes at the end and it does not render like Html select options how can I remove the quotes that my options should be shown in its normal mode.
when I inspect element in browser the options are shown like this:
"<option value=1>Kabul</option><option selected='selected' value=2>Mazar</option><option selected='selected' value=3>Parwan</option><option value=4>Herat</option><option value=5>Badakhshan</option><option value=6>Takhar</option><option value=7>Smanagan</option><option selected='selected' value=8>Zabul</option>"
or you suggest me another way for this I am new to ASP.Net
I agree with #ChrFin Answer but with some more details which I hope will solve your problem
// GET: Project/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var edata = db.Projects.Find(id);
//check if data
if (edata == null)
return HttpNotFound();
//IEnumerable<SelectListItem> items = db.Provinces.Select(c => new SelectListItem { Value = c.ID.ToString(), Text = c.Name });
//ViewBag.ProvinceId = items;
//---Get all provice-----
var Prov = from c in db.Provinces select c;
//------get province ids---------------
var prov_id = from o in db.ProRel where o.ProjectId == id select o.ProvinceIds;
List<int> mid_list = new List<int>();
foreach (var p_ids in prov_id)
{
mid_list.Add(p_ids);
}
var options = new List<SelectListItem>();
foreach (var p_itmes in Prov)
{
var item = new SelectListItem();
if (mid_list.Contains(p_itmes.ID))
item.Selected = true;
item.Value = p_itmes.ID.ToString();
item.Text = p_itmes.Name;
options.Add(item);
}
ViewBag.options = options;
return View(edata);
}
and inside your view add the following extra attribute:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
#Html.DropDownList("prov", (List<SelectListItem>)ViewBag.options, htmlAttributes: new { #class = "form-control", #multiple = "multiple" })
</div>
</div>
Short answer was already given by Marcos via his comment, but in general thats not how you create a select tag within MVC 5:
Controller:
public ActionResult Edit(int? id)
{
// other code
var options = new List<SelectListItem>();
foreach (var p_itmes in Prov)
{
var item = new SelectListItem();
if (mid_list.Contains(p_itmes.ID))
item.Selected = true;
item.Value = p_itmes.ID.ToString();
item.Text = p_itmes.Name;
options.Add(item);
}
ViewBag.options = options;
return View(edata);
}
View:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
#Html.DropDownList("prov", (List<SelectListItem>)ViewBag.options,
htmlAttributes: new { multiple = "multiple" })
</div>
</div>

Categories