How to show partial view - c#

I have a page with information, i want to add there a list (in a form of table) within a partial view. User has to have an ability to sort it by switching radio box.
My problem: the code works fine (i have tried in a separate view), but when i try to switch radio button (they submit page on change and activate 2nd method, which create new model according to radio button) i get html code only from my partial view.
In other words:
i want to : HTML from view1 + HTML from myPartial
i get: only HTML from myPartial
I suppose problem is here (calling my myPartial):
#Html.Action("_ShowEmployeeProjects", "Employee")
But when i try to use this:
#Html.Partial("Partial/_ShowEmployeeProjects")
I get this:
The model item passed into the dictionary is of type
'BTGHRM.Models.EmployeeJobDataViewModel', but this dictionary requires
a model item of type
'System.Collections.Generic.List`1[BTGHRM.Models.EmployeeProjectHistoryModel]'.
My controllers code:
public PartialViewResult _ShowEmployeeProjects()
{
int EmpId = HRMSession.SelectedEmployeeId;
using (var db = new HRMEntities())
{
List<EmployeeProjectHistoryModel> list = (from t1 in db.ProjectWorkers
join t2 in db.Projects
on t1.ProjectId equals t2.ProjectId
where (t1.WorkerId == EmpId && t1.IsActive == true)
select new EmployeeProjectHistoryModel()
{
ProjectName = t2.ProjectName,
Activity = t1.Activity,
StartDate = t1.StartDate,
EndDate = t1.EndDate
}).ToList();
return PartialView("Partial/_ShowEmployeeProjects",list);
}
}
[HttpPost]
public PartialViewResult _ShowEmployeeProjects(string ActiveOnlySelect)
{
int EmpId = HRMSession.SelectedEmployeeId;
List<EmployeeProjectHistoryModel> list;
using (var db = new HRMEntities())
{
if (ActiveOnlySelect.Equals("both"))
{
list = (from t1 in db.ProjectWorkers
join t2 in db.Projects
on t1.ProjectId equals t2.ProjectId
where (t1.WorkerId == EmpId)
select new EmployeeProjectHistoryModel()
{
ProjectName = t2.ProjectName,
Activity = t1.Activity,
StartDate = t1.StartDate,
EndDate = t1.EndDate
}).ToList();
list.OrderBy(x => x.StartDate);
}
else
{
list = (from t1 in db.ProjectWorkers
join t2 in db.Projects
on t1.ProjectId equals t2.ProjectId
where (t1.WorkerId == EmpId && t1.IsActive == true)
select new EmployeeProjectHistoryModel()
{
ProjectName = t2.ProjectName,
Activity = t1.Activity,
StartDate = t1.StartDate,
EndDate = t1.EndDate
}).ToList();
list.OrderBy(x => x.StartDate);
}
}
return PartialView("Partial/_ShowEmployeeProjects", list);
}
My partial:
#model List<BTGHRM.Models.EmployeeProjectHistoryModel>
#using (Html.BeginForm("_ShowEmployeeProjects", "Employee", FormMethod.Post, new { type = "main" }))
{
<table>
<tr>
<td>
#Html.RadioButton("ActiveOnlySelect", "activeonly", true, new { id = "ActiveOnlySelect0", onchange = "this.form.submit();" })
<label for="ActiveOnlySelect0">#Resources.Localization.show_only_actual</label>
</td>
</tr>
<tr>
<td>
#Html.RadioButton("ActiveOnlySelect", "both", new { id = "ActiveOnlySelect1", onchange = "this.form.submit();" })
<label for="ActiveOnlySelect1">#Resources.Localization.show_all_data</label>
</td>
</tr>
</table>
}
#{
WebGrid grid = new WebGrid(Model, canSort: false, rowsPerPage: 15);
if (Model.Any())
{
#grid.GetHtml(
tableStyle: "table",
headerStyle: "table_HeaderStyle",
footerStyle: "table_PagerStyle",
rowStyle: "table_RowStyle",
alternatingRowStyle: "table_AlternatingRowStyle",
selectedRowStyle: "table_SelectedRowStyle",
columns: grid.Columns(
grid.Column("ProjectName", Resources.Localization.project, style: "p30"),
grid.Column("Activity", Resources.Localization.activity, style: "p30"),
grid.Column("StartDate", Resources.Localization.start_date, format: #<text>
#if (item.StartDate != null)
{
<span class="display-mode"><label id="StartDateLabel">#item.StartDate.ToShortDateString()</label></span>
#Html.Hidden("Model.StartDate", (object)item.StartDate.ToShortDateString())
}
else
{
<span> </span>
}</text>, style: "p10"),
grid.Column("EndDate", Resources.Localization.end_date, format: #<text>
#if (item.EndDate != null)
{
<span class="display-mode"><label id="EndDateLabel">#item.EndDate.ToShortDateString()</label></span>
#Html.Hidden("Model.EndDate", (object)item.EndDate.ToShortDateString())
}
else
{
<span> </span>
}</text>, style: "p10")
)
)
}
}

It looks like you are passing a wrong model to your partial. The structure will be:
In your principal Layout:
#model System.Collections.Generic.List[BTGHRM.Models.your_model]
<!-- DO YOUR HTML´S STUFF. You can access to your_model.employee´s list -->
#Html.Partial("Partial/_ShowEmployeeProjects", Model.projects)
In your Partial, remember to get the model which you are passing from your main layout:
#model System.Collections.Generic.List[BTGHRM.Models.your_model.projects]
<!-- DO YOUR HTML´S STUFF -->
Then, in your controller, you must return return:
[HttpPost]
public PartialViewResult _ShowEmployeeProjects(string ActiveOnlySelect)
{
// DO YOUR MAGIC
// model should be a List[BTGHRM.Models.your_model]
PartialView("Partial/_ShowEmployeeProjects", model);
}
Model:
public class your_model
{
List<Employee> employees;
List<Project> projects;
.....
}

Related

How to persist filterdata when sorting ASP.NET CORE MVC

I'm trying to make a table that has searching, sorting, and filtering (any number of available filters). When I sort the filters get overwritten and I'm not sure how to make sure they stay in the querystring since they are stored in the model as an array of strings.
I've tried using the ViewBag and the asp-route-varName tag but it didn't work since it's an array. I thought since they are all in the same form that they should just append to the querystring not overwrite it. The sort and search works since search is just a string. The filter and search works not entirely sure why.
View:
#model ScenarioLake.Api.Host.WebApplication.Models.MasterModel;
<form asp-controller="FileList" asp-action="Index" method="get">
<p>
Title: <input type="text" name="SearchString" />
<input type="submit" value="Filter" />
<a asp-action="Index">Full List</a>
</p>
<select class="chosen-select" multiple="multiple" name="filters" asp-for="filters"
asp-items="Model.filterModel.filters[0].values;"></select>
<input type="submit" />
<table class="table">
<thead>
<tr>
<th>
<a asp-controller="FileList" asp-action="Index" asp-route-searchString="#Model.searchString" asp-route-sortOrder="#ViewData["NameSortParm"]">
#Html.DisplayNameFor(model => model.files.FirstOrDefault().Name)
</a>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.files)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Guid">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Guid">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Guid">Delete</a>
</td>
</tr>
}
</tbody>
</table>
</form>
Model:
public class MasterModel
{
public FilterFileModel filterModel { get; set;}
public List<FileDisplay> files;
public string[] filters { get; set; }
public string searchString { get; set; }
}
Controller Index Method:
public async Task<IActionResult> Index(string sortOrder, string searchString, MasterModel model)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
IGetFileListHandler fileListHandler = _restServiceFactory.CreateGetFileListHandler();
GetFileListRequest fileListRequest = new GetFileListRequest();
IGetFileListResponse response = await fileListHandler.ProcessRequest(fileListRequest);
var items = new List<FileDisplay>();
IGetFileAttributesHandler fileAttributesHandler = _restServiceFactory.CreateGetFileAttributesHandler();
GetFileAttributesRequest fileAttributesRequest = new GetFileAttributesRequest();
IGetFileAttributesResponse fileAttributesResponse = await fileAttributesHandler.ProcessRequest(fileAttributesRequest);
IGetFileFileAttributeHandler fileFileAttributesHandler = _restServiceFactory.CreateGetFileFileAttributeHandler();
GetFileFileAttributeRequest fileFileAttributesRequest = new GetFileFileAttributeRequest();
IGetFileFileAttributeResponse fileFileAttributesResponse = await fileFileAttributesHandler.ProcessRequest(fileFileAttributesRequest);
var fileFileAttribute = fileFileAttributesResponse.FileFileAttributes;
IEnumerable<Entities.Public.Interfaces.IFile> responseFilteredFiles = response.Files;
FilterFileModel fileFilter = new FilterFileModel();
fileFilter.filters = new List<FileFilter>();
if (!ReferenceEquals(fileAttributesResponse, null) && !ReferenceEquals(fileAttributesResponse.Values, null))
{
fileFilter.types = fileAttributesResponse.Values.Select(s => s.Type).Distinct().ToList(); // query fileattribute repo to get all types of filters
foreach (var type in fileFilter.types)
{
FileFilter filter = new FileFilter();
filter.type = type;
filter.values = fileAttributesResponse.Values.Where(s => s.Type == type).Select(s => new SelectListItem()
{
Value = s.Value,
Text = s.Value
}).Distinct().ToList();
fileFilter.filters.Add(filter);
}
}
if (!ReferenceEquals(response, null) && !ReferenceEquals(response.Files, null))
{
if (!String.IsNullOrEmpty(searchString))
{
responseFilteredFiles = responseFilteredFiles.Where(s => s.FileName.Contains(searchString));
model.searchString = searchString;
}
switch(sortOrder)
{
case "name_desc":
responseFilteredFiles = responseFilteredFiles.OrderByDescending(s => s.FileName);
break;
default:
responseFilteredFiles = responseFilteredFiles.OrderBy(s => s.FileName);
break;
}
}
if (model.filters != null)
{
if (model.filters.Length != 0)
{
IEnumerable<int> attributeIds = fileAttributesResponse.Values.Where(s => model.filters.Contains(s.Value)).Select(s => s.FileAttributeId);
IEnumerable<int> fileIds = fileFileAttribute.Where(s => attributeIds.Contains(s.FileAttributeId)).Select(s => s.FileId);
responseFilteredFiles = responseFilteredFiles.Where(s => fileIds.Contains(s.FileId));
}
}
foreach (var item in responseFilteredFiles)
{
var file = new FileDisplay()
{
Name = item.FileName,
Guid = item.Guid,
FileId = item.FileId
};
items.Add(file);
}
model.filterModel = fileFilter;
model.files = items;
return View(model);
}
The expected result is that the filter and search data persists when a user changes the sort. The actual results are only the search persists, I don't care about the sort persisting when the filters or search are changed.

how to get one item of the list in a foreach ViewBag mvc 5

I want to get all the student have the ContractStatus == "Pending" in foreach and make a link to Edit the student
<div class="row">
#{ foreach (var studentCohort in ViewBag.CohortSubscriptionId)
{
<div class="col-md-5">
#{
var link = Html.ActionLink((string) studentCohort.ContractStatus, "Edit", "CohortSubscriptions", new { id = (object) studentCohort.ContractStatus }, new { #class ="form-control"});
var contractStatus = studentCohort.ContractStatus == "Pending" ? link : studentCohort;
}
#studentCohort.FullName (#studentCohort.contractStatus)
</div>
}
}
</div>
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cohorts cohorts = db.Cohorts.Find(id);
if (cohorts == null)
{
return HttpNotFound();
}
var studentByCohort = db.Enrolled_Students.Where(x => x.CohortId == id).Select(x => new StudentCohortViewModel
{
CohortId = x.CohortId,
FirstName = x.FirstName,
LastName = x.LastName,
ContractStatus = x.ContractStatus
}).Distinct().ToList();
ViewBag.CohortSubscriptionId = studentByCohort;
return View(cohorts);
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''CodeboxxSchoolPortal.Models.StudentCohortViewModel' does not contain a definition for 'contractStatus''
Your choice in variable names and reassignments are hurting you here. Consequently, you're getting your types mixed and the errors you experience.
Instead of the ternary conditional (c ? a : b), I suggest using basic if/else which is easier to read and write.
<div class="row">
#foreach(StudentCohortViewModel studentCohort in ViewBag.CohortSubscriptionId)
{
if (studentCohort.ContractStatus == "Pending")
{
<text>
#studentCohort.FullName (#Html.ActionLink(studentCohort.ContractStatus,
"Edit",
"CohortSubscriptions",
new { id = student.ContractStatus },
new { #class = "form-control" }))
</text>
}
else
{
<text>
#studentCohort.FullName (#studentCohort.ContractStatus)
</text>
}
}
</div>
To help with identifying the correct type, instead of var studentCohort use the more explicit StudentCohortViewModel studentCohort.
change
(#studentCohort.contractStatus)
to
(#studentCohort.ContractStatus)
in your Razor view.

Get single column results as a list from a stored procedure using LINQ

Here is my code I'm trying to get the list of Equipment from a stored procedure and the code scenario is very different than others as I can't make it work.
I've tried many ways as one can see in the given code but nothing works
public ActionResult Test()
{
var model = new ViewModels()
{
ModelEquipmentRequestResult = new List<EquipmentRequest_Result>()
{
new EquipmentRequest_Result()
{
EquipmentName = db.EquipmentRequest().ToList().ToString()
// (from a in new db.EquipmentRequest
//select new EquipmentRequest { a.EquipmentName}).ToList();
// ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<EquipmentRequest_Result>("EquipmentRequest").ToList().TooString()
//db.EquipmentRequest().AsQueryable<EquipmentRequest_Result>(),
//custq.AsEnumerable()
// .Select(o => new EquipmentRequest_Result() {
// EquipmentName = o.EquipmentName
//}).ToList()
}
},
ModeleEquipmentSpViewModel = new EquipmentSpViewModel()
};
ViewBag.project = db.PMSProjects.ToList();
return View(model);
}
This line of code
EquipmentName = db.EquipmentRequest().ToList().ToString()
returns something like this:
EquipmentName
System.Collections.Generic.List`1[ProjectManagementSystem.EntityDataModel.EquipmentRequest_Result]
Here is the stored procedure query:
SELECT
e.EquipmentName,
NULL AS Id,
NULL AS EquipmentRequestId,
NULL AS EquipmentId,
NULL AS Planned,
NULL AS Actual,
NULL AS Remarks
FROM
PECEquipment AS e
Here is the view with which I bind this
#model ProjectManagementSystem.ViewModel.ViewModels
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>TestPartail</title>
</head>
<body>
<div>
#for (int i = 0; i < Model.ModelEquipmentRequestResult.Count; i++)
{
<div>
#Html.LabelFor(m => m.ModelEquipmentRequestResult[i].EquipmentName)
#Html.DisplayFor(m => m.ModelEquipmentRequestResult[i].EquipmentName)
</div>
<div>
#Html.LabelFor(m => m.ModelEquipmentRequestResult[i].Planned)
#Html.EditorFor(m => m.ModelEquipmentRequestResult[i].Planned)
</div>
<div>
#Html.LabelFor(m => m.ModelEquipmentRequestResult[i].Actual)
#Html.EditorFor(m => m.ModelEquipmentRequestResult[i].Actual)
</div>
}
</div>
</body>
</html>
Try this:
List<EquipmentRequest_Result> output = db
.EquipmentRequest()
.Select(x=> new EquipmentRequest_Result { EquipmentName = x.EquipmentName })
.ToList()
EDIT: Specifically for this question's scenario
var model = new ViewModels()
{
ModelEquipmentRequestResult = db
.EquipmentRequest()
.Select(x=> new EquipmentRequest_Result { EquipmentName = x.EquipmentName })
.ToList(),
ModeleEquipmentSpViewModel = new EquipmentSpViewModel()
};
return View(model);
Upon clarification:
var model = new ViewModels()
{
ModelEquipmentRequestResult = db.EquipmentRequest().Select(result => new EquipmentRequest_Result
{
EquipmentName = r.EquipmentName,
Planned = r.Planned, //replace with DB column name
Actual = r.Actual //replace with DB column name
}).ToList(),
ModeleEquipmentSpViewModel = new EquipmentSpViewModel()
};
The answer above does the same thing.

How to Bind a DropDownList Text Value to another DropDownList using Kendo UI for MVC?

I'm using the Kendo UI for ASP.NET MVC and need to bind the selected value of a dropdown list to another dropdownlist. I want the user to only be shown the citiy entries that are applicable to the State selection they choose. My dropdownlist is as follows:
<div id="bindcity" class="inr_div" data-bind="visible: showFromChooseCity">
<h5 class="inr_hd">City<span>*</span>:</h5>
#(Html.Kendo().DropDownList()
.Name("fromCity")
.DataTextField("name")
.DataValueField("id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCity", "Quote");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
)
I setup several controller classes as follows:
public JsonResult GetZips()
{
FreightEntities freight = new FreightEntities();
var zips = freight.ZipCodes.AsQueryable();
var city = freight.ZipCodes.AsQueryable();
if (city != null)
{
zips = zips.Where(z => z.Zip = zips);
}
return Json(freight.ZipCodes.Select(z => new {Zip = z.Zip}), JsonRequestBehavior.AllowGet);
}
public JsonResult GetCity()
{
FreightEntities freight = new FreightEntities();
var state = freight.ZipCodes.AsQueryable();
var city = freight.ZipCodes.AsQueryable();
if (state != null)
{
city = city.Where(s => s.State = state);
}
return Json(freight.ZipCodes.Select(s => new { State = s.State }), JsonRequestBehavior.AllowGet);
}
public JsonResult GetState()
{
FreightEntities freight = new FreightEntities();
return Json(freight.ZipCodes.Select(s => new {State = s.State }), JsonRequestBehavior.AllowGet);
}
The above code now gives the error:
Cannot implicitly convert type 'System.Linq.IQueryable<FRCV2.Models.ZipCode>' to 'string'
Since I'm not using an ID field in my entities, what's the appropriate way of comparing the fields above?
How do I achieve this cascading dropdownlist effect?

How to bind value to dropdownlist in asp.net mvc?

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();
}

Categories