In my views, I have a few drop-down lists that I use to get the ID and show the value to the user so they know what they are choosing. But in the view that I use to list everything that has already been added, it shows the chosen ID, but I want the name to appear
I tried this but it always shows the status that has the ID 1, which is the status "Active"
#Html.DropDownListFor(modelItem => item.status,
(SelectList)ViewBag.listStatus,
new { #class disabled = "" })
//controller
{
public ActionResult listStatus()
{
var list= ListsDAO.listStatus();
return View(list);
}
}
//DAO
{
public static IEnumerable<LISTS> listStatus()
{
using (var ctx = new PadraoEntities())
{
var result= from lists in ctx.LISTS
where lists.TYPE_LIST== "STATUS"
select new
{
lists.IDE_LIST,
lists.DES_LIST,
lists.VLR_LIST
};
var list= new List<LISTS>();
foreach (var item in result)
{
list.Add(new LISTS()
{
IDE_LIST = item.IDE_LIST,
VLR_LIST = item.VLR_LIST,
DES_LIST = item.DES_LIST
});
}
return list;
}
}
}
//view add
<div class="form-group">
#Html.LabelFor(model => model.status, htmlAttributes: new { #class = "control -Label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.status(SelectList)ViewBag.listStatus, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.status, "", new { #class = "text-danger" })
</div>
</div>
//view list
{
#Html.DropDownListFor(modelItem => item.ststus,(SelectList)ViewBag.listStatus,new { disabled = "" })
}
when listing id 1, I expected "active" to appear, id 2 shows "inactive", etc
Try this //controller
public ActionResult listStatus()
{
ViewBag.Status = new SelectList(//Code to get id and its property, "StatusId", "Status");
var list= ListsDAO.listStatus();
return View(list);
}
//View
<div class="form-group">
#Html.LabelFor(model => model.Status, "TaskId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Status", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>
Related
I have created a cascading dropdown for my application, on the create it works fine but I am struggling to implement the same on the edit. Please find the code below.
Ho do I use the same methodology for getting all the cascaded values for the edit so the user can know what are the associated values to the main cascaded dropdown?
CREATE
<div class="form-group">
#Html.LabelFor(model => model.IndicatorID, "Indicator", htmlAttributes: new { #class =
"control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.IndicatorID, new SelectList(ViewBag.IndicatorID as
System.Collections.IEnumerable, "IndicatorID", "IndicatorName"),
"Select a Indicator", new { id = "ddlIndicators" })
#Html.ValidationMessageFor(model => model.IndicatorID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IndGrID, "Group IndGrID", htmlAttributes: new { #class =
"control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(Model => Model.IndGrID, new
SelectList(Enumerable.Empty<SelectListItem>(), "GroupId", "GroupName"),
"Select a Subgroup", new { id = "ddlGroup" })
#Html.ValidationMessageFor(model => model.IndGrID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubGroupID, "Sub Group SubGroupID", htmlAttributes: new { #class
= "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(Model => Model.SubGroupID, new
SelectList(Enumerable.Empty<SelectListItem>(), "SubGroupID", "SubGroupName"),
"Select a Subgroup", new { id = "ddlSubGroup" })
#Html.ValidationMessageFor(model => model.SubGroupID, "", new { #class = "text-danger" })
</div>
</div>
$(document).ready(function () {
$("#ddlIndicators").change(function () {
var indicatorID = $(this).val();
$.getJSON("../Indicator_SubGroup/LoadSubGroupByIndicatorID", { indicatorID:
indicatorID },
function (classesData) {
var select = $("#ddlGroup");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select group"
}));
$.each(classesData, function (index, itemData) {
//alert(classesData);
//alert(itemData);
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
$("#ddlGroup").change(function () {
var subGroupId = $(this).val();
$.getJSON("../Indicator_SubGroup/LoadSubGroupByGroupID", { subGroupId: subGroupId
},
function (marksData) {
var select = $("#ddlSubGroup");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select Subgroup"
}));
$.each(marksData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
Controller:
private IList<Ref_Indicator_Group> GetGroup(int groupid)
{
return db.Ref_Indicator_Group.Where(m => m.GroupId == groupid).ToList();
}
private IList<Ref_SubGroup> GetSubGroup(int subGroupid)
{
return db.Ref_SubGroup.Where(m => m.Indicator_GroupID == subGroupid).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadSubGroupByIndicatorID(/*string groupid*/int indicatorID)
{
var gi = db.INDICATORS.Where(d => d.IndicatorID == indicatorID).FirstOrDefault();
var subgrouplist = this.GetGroup(Convert.ToInt32(gi.GroupID));
var subgroupData = subgrouplist.Select(m => new SelectListItem()
{
Text = m.GroupName,
Value = m.GroupId.ToString(),
});
return Json(subgroupData, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadSubGroupByGroupID(string subGroupId)
{
var subgroupList = this.GetSubGroup(Convert.ToInt32(subGroupId));
var subgroupData = subgroupList.Select(c => new SelectListItem()
{
Text = c.SubGroupName,
Value = c.SubGroupID.ToString(),
});
return Json(subgroupData, JsonRequestBehavior.AllowGet);
}
EDIT
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Indicator_SubGroup indicator_SubGroup = db.Indicator_SubGroup.Find(id);
if (indicator_SubGroup == null)
{
return HttpNotFound();
}
ViewBag.IndicatorID = new SelectList(db.INDICATORS, "IndicatorID", "IndicatorName",
indicator_SubGroup.IndicatorID);
ViewBag.SubGroupID = new SelectList(db.Ref_SubGroup, "SubGroupID", "SubGroupName",
indicator_SubGroup.SubGroupID);
ViewBag.IndGrID = new SelectList(db.Ref_Indicator_Group, "GroupId", "GroupName",
indicator_SubGroup.IndGrID);
return View(indicator_SubGroup);
}
When I fill in the information on my add product page and try to save, I get the error.
public ActionResult Create()
{
List<SelectListItem> values= (from i in db.Categories.ToList()
select new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}
).ToList();
ViewBag.val = values;
return View();
}
View
<div class="form-group">
#Html.LabelFor(model => model.CategoryId, "CategoryId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=> m.CategoryId ,(List<SelectListItem>)ViewBag.val, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryId, "", new { #class = "text-danger" })
</div>
</div>
Error
System.InvalidOperationException: 'The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'.'
ViewBag doesn't require type-casting, try changing your code in View from
#Html.DropDownListFor(m=> m.CategoryId ,(List)ViewBag.val, new { #class = "form-control" })
to
#Html.DropDownListFor(m=> m.CategoryId ,#ViewBag.val, new { #class = "form-control" })
Or, you may also refer this SO answer
and use something like below -
#Html.DropDownListFor(m => m.ContribType,
new SelectList(#ViewBag.ContribTypeOptions, "ContribId",
"Value", Model.ContribTypeOptions.First().ContribId),
"Select, please")
Problem is occurring here:
#Html.DropDownList("KategoriId", null, htmlAttributes: new { #class = "form-control" })
Here is my Controller:
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategoris, "KategoriId", "KategoriAdi");
return View();
}
Here is my View:
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.KategoriId, "KategoriId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("KategoriId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.KategoriId, "", new { #class = "text-danger" })
</div>
</div>
You can do this Type Casting ViewBag to IEnumerable<SelectListItem> in CSHTML:
CSHTML Code:
#Html.DropDownList("your_key", (IEnumerable<SelectListItem>)ViewBag.KategoriId, "--Select Any--", new { #class = "form-control"})
Controller code:
IList<SelectListItem> items = new List<SelectListItem>();
foreach (var item in db.Kategoris.ToList())
{
SelectListItem sellist = new SelectListItem();
sellist.Value = item.code.ToString();
sellist.Text = item.name;
items.Add(sellist);
}
ViewBag.KategoriId = items; // at the end this item should be list of `SelectListItem`
Write your #Html.DropDownList() as follows:
#Html.DropDownList("KategoriId", ViewBag.KategoriId as SelectList,"Select Ketegory Id", htmlAttributes: new { #class = "form-control" })
This should fix your problem!
I intend to display a list of employees with about five columns on the left side of my razor view, and on selecting any employee (row), display details of the employee as a readonly partial view on the right - as in the image below. My wish is to reuse the details form later in another view to add/update records.
My controller is shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mymvc.Controllers
{
public class EmpController : Controller
{
private readonly MyEntities _db = new MyEntities();
private IEnumerable<vEmployee> _Employees;
// GET: Employee
public ActionResult Index()
{
ViewData["ModuleName"] = "Active Employees";
ViewData["deptIDList"] = _db.lu_Department.OrderBy(e => e.Dept);
ViewData["jobTitleIDList"] = _db.lu_JobTitle.OrderBy(e => e.JobTitle);
ViewData["genderList"] = _db.lu_Gender.OrderBy(e => e.Gender);
ViewData["ethnicityList"] = _db.lu_Ethnicity.OrderBy(e => e.Ethnicity);
ViewData["nationalityList"] = _db.lu_Nationality.OrderBy(e => e.Nationality);
ViewData["staffLocationList"] = _db.lu_StaffLocation.OrderBy(e => e.StaffLocation);
ViewData["notchList"] = _db.lu_EmploymentGradeNotch.OrderBy(e => e.Notch);
ViewData["salutationList"] = _db.lu_Salutation.OrderBy(e => e.Title);
return View();
}
public ActionResult EmployeeDetails(int employeeID = 0)
{
vEmployee SelectedEmployee = null;
ViewData["deptIDList"] = _db.lu_Department.OrderBy(e => e.Dept);
ViewData["jobTitleIDList"] = _db.lu_JobTitle.OrderBy(e => e.JobTitle);
ViewData["genderList"] = _db.lu_Gender.OrderBy(e => e.Gender);
ViewData["ethnicityList"] = _db.lu_Ethnicity.OrderBy(e => e.Ethnicity);
ViewData["nationalityList"] = _db.lu_Nationality.OrderBy(e => e.Nationality);
ViewData["staffLocationList"] = _db.lu_StaffLocation.OrderBy(e => e.StaffLocation);
ViewData["notchList"] = _db.lu_EmploymentGradeNotch.OrderBy(e => e.Notch);
ViewData["salutationList"] = _db.lu_Salutation.OrderBy(e => e.Title);
try
{
if (employeeID == 0)
employeeID = _db.Employees.OrderBy(m => m.EmployeeNumber).First().EmployeeID;
if (_Employees == null)
_Employees = GetEmployees();
SelectedEmployee = _Employees.First(e => e.EmployeeID == employeeID);
}
catch (Exception e)
{
var msg = e.Message;
}
return View(SelectedEmployee);
}
private IEnumerable<vEmployee> GetEmployees()
{
IEnumerable<vEmployee> emp = (from e in _db.Employees
join c in _db.Contacts on e.EmployeeID equals c.EmployeeID
join g in _db.lu_EmploymentGradeNotch on e.NotchID equals g.NotchID
join u in _db.lu_Salutation on c.SalutationID equals u.TitleID into sal
from u in sal.DefaultIfEmpty()
join s in _db.lu_SUBDepartment on e.SubDeptID equals s.SubDeptID into sde
from s in sde.DefaultIfEmpty()
join l in _db.lu_StaffLocation on e.StaffLocationID equals l.StaffLocationID into cl
from cm in cl.DefaultIfEmpty()
join t in _db.lu_Ethnicity on c.EthnicityID equals t.EthnicityID into eth
from et in eth.DefaultIfEmpty()
join n in _db.lu_Nationality on c.NationalityID equals n.NationalityID into nt
from nt1 in nt.DefaultIfEmpty()
where c.ContactTypeID == 1 && e.EmploymentStatusID == 1
select new vEmployee
{
EmployeeID = e.EmployeeID,
EmployeeNumber = e.EmployeeNumber,
DeptID = e.DeptID,
SubDeptID = e.SubDeptID,
JobTitleID = e.JobTitleID,
ReportsToID = e.ReportsToID,
NotchID = g.NotchID,
HireDate = e.HireDate,
StaffLocationID = e.StaffLocationID,
FirstName = c.FirstName,
LastName = c.LastName,
MiddleName = c.MiddleName,
FullName = c.FirstName + (c.MiddleName == null ? "" : " " + c.MiddleName) + " " + c.LastName + " (" + u.Title + ")",
SalutationID = c.SalutationID,
GenderID = c.GenderID,
EthnicityID = c.EthnicityID,
NationalityID = c.NationalityID,
Photograph = e.Photograph
})
.AsEnumerable()
.OrderBy(m => m.EmployeeNumber)
.ThenBy(m => m.FirstName);
return emp;
}
public ActionResult ActiveEmployees_Read([DataSourceRequest] DataSourceRequest request)
{
_Employees = GetEmployees();
return Json(_Employees.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
}
}
}
My Main Index view:
#using Mymvc.Models
#model Mymvc.Models.vEmployee
#using System.Collections
<div class="col col-xs-6">
#(Html.Kendo().Grid<vEmployee>()
.Name("EmployeesList")
.Columns(columns =>
{
columns.Bound(p => p.EmployeeNumber).Width(35);
columns.Bound(p => p.FirstName).Width(60);
columns.Bound(p => p.LastName).Width(60);
columns.ForeignKey(p => p.JobTitleID, (IEnumerable)ViewData["jobTitleIDList"], "JobTitleID", "JobTitle")
.Width(60);
columns.ForeignKey(p => p.DeptID, (IEnumerable)ViewData["deptIDList"], "DeptID", "Dept")
.Width(60);
})
.Events(e => e.Change("Grid_OnRowSelect"))
.Events(e => e.DataBound("Grid_OnDataBound"))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
.ServerOperation(false)
.Events(events => events.Error("grid_error")) // Handle the "error" event
.Model(model =>
{
model.Id(m => m.EmployeeID);
model.Field(m => m.EmployeeID).Editable(false);
})
.Read(read => read.Action("ActiveEmployees_Read", "Employee"))
)
.Filterable()
.Pageable()
.Sortable()
.Selectable()
)
</div>
#Html.Partial("_EmployeeDetails");
<script type="text/javascript">
Grid_OnDataBound = function (e) {
var grid = $("#EmployeesList").data("kendoGrid");
grid.select(e.sender.tbody.find("tr:first"));
}
Grid_OnRowSelect = function (e) {
var data = this.dataItem(this.select());
var empID = data.id;//IMP
$.ajax({
url: '/Employee/EmployeeDetails',
type: "GET",
//dataType: "JSON",
data: { 'employeeID': empID }
});
}
</script>
Upon selecting any employee on my list my OnDataBound and OnRowSelect events send the selected EmployeeID to my EmployeeDetails controller method.
My PartialView:
#model Mymvc.Models.vEmployee
#using System.Collections
<div class="col col-xs-6">
#using (Html.BeginForm("EmployeeDetails", "Employee"))
{
<div class="container">
<div class="col-md-8 well">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div id="updateMsg" class="demo-section k-content"></div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
#Html.TextBoxFor(model => model.LastName, new { style = "width: 400px" })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
#Html.TextBoxFor(model => model.FirstName, new { style = "width: 400px" })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleName, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
#Html.TextBoxFor(model => model.MiddleName, new { style = "width: 400px" })
#Html.ValidationMessageFor(model => model.MiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SalutationID, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-2">
#Html.DropDownListFor(model => model.SalutationID, new SelectList((IEnumerable)ViewData["salutationList"], "TitleID", "Title"))
#Html.ValidationMessageFor(model => model.SalutationID, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.GenderID, htmlAttributes: new { #class = "control-label col-md-2 col-md-offset-2" })
<div class="col-md-1">
#Html.DropDownListFor(model => model.GenderID, new SelectList((IEnumerable)ViewData["genderList"], "GenderID", "Gender"))
#Html.ValidationMessageFor(model => model.GenderID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NationalityID, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-1">
#Html.DropDownListFor(model => model.NationalityID, new SelectList((IEnumerable)ViewData["nationalityList"], "NationalityID", "Nationality"))
#Html.ValidationMessageFor(model => model.NationalityID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EthnicityID, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-1">
#Html.DropDownListFor(model => model.EthnicityID, new SelectList((IEnumerable)ViewData["ethnicityList"], "EthnicityID", "Ethnicity"))
#Html.ValidationMessageFor(model => model.EthnicityID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Photograph, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
#Html.TextBoxFor(model => model.Photograph, new { style = "width: 180px" })
#Html.ValidationMessageFor(model => model.Photograph, "", new { #class = "text-danger" })
</div>
</div>
</div>
<style>
.demo-section {
text-align: center;
line-height: 4em;
}
</style>
</div>
</div>
}
</div>
My Challenge:
I cannot populate my details partialview with model information on selecting an employee on the left list. When I view the SelectedEmployee object in the EmployeeDetails method in debug, the details (lastname, firstname, etc.) can be seen confirming my ajax method is working well.
What am I doing wrong here? Also, is there a better method of presenting list and detail in the same view in mvc?
Thanks!
#Html.Partial("_EmployeeDetails") only call _EmployeeDetails view. This code cannot call Controller _EmployeeDetails method.
So, as you need , Access the view through the controller
Change #Html.Partial("_EmployeeDetails") to #Html.Action("_EmployeeDetails");
_EmployeeDetails action can be take selected Id parameter.
#Html.Action("_EmployeeDetails", new { id = yourSelectedRowIdValue })
You can find the selected id and return from the _EmployeeDetails method spesific detail data.
public ActionResult _EmployeeDetails (int id)
{
// var employeeDetail = find _EmployeeDetail using by id
return View (employeeDetail );
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,FromTime,ToTime,CustomerID,UserID,Description,Type,CreatedTime")] Schedule schedule)
{
if (ModelState.IsValid)
{
db.Entry(schedule).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CustomerID = new SelectList(db.Customers, "ID", "Name", schedule.CustomerID);
ViewBag.UserID = new SelectList(db.Users, "ID", "Name", schedule.UserID);
//return View(schedule);
return RedirectToRoute("Default", new { controller = "Schedules", action = "Index" });
}
<div class="form-group">
#Html.LabelFor(model => model.FromTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FromTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FromTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ToTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ToTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ToTime, "", new { #class = "text-danger" })
</div>
</div>
The type of FromTime and ToTime is long and i want to display it as Time and then save it back as long.
If I have a type of long in the database and i need to display it as Time in Model View Controller ASP.Net then save it as a long again into the database. How can i do this?