ASP.NET MVC DropDownList displaying "Id" instead of "Description" - c#

I've been doing some tutorials in ASP.NET MVC and decided to try something I hadn't seen yet.
I have two tables: Patient and Classification. I want to be able to create a new Classification, then when I Create or Edit a new Patient, I can choose a Classification.
Right now, as an example of what I have in my DropDownList, lets say I have cat, dog and fish. If I select cat, the value displayed will be 1 instead of the actual word "cat."
My question is can this be achieved with the code I have or does it need a complete rewrite? And if you have any other general suggestions let me know.
My Controller:
private PatientContext db = new PatientContext();
private ClassificationContext dbCC = new ClassificationContext();
public ActionResult Index(string sortOrder)
{
return View();
}
public ActionResult Create([Bind(Include = "PatientId,First_Name,Last_Name,Address,City,State,Zipcode,Phone,ClassificationId")] Patient patient)
{
if (ModelState.IsValid)
{
db.Patients.Add(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Classifications = new SelectList(dbCC.Classifications, "ClassificationId", "Description");
return View(patient);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patients.Find(id);
if (patient == null)
{
return HttpNotFound();
}
ViewBag.Classifications = new SelectList(dbCC.Classifications, "ClassificationId", "Description");
return View(patient);
}
Patient Model:
public class Patient
{
public int PatientId { get; set; }
[DisplayName("Classification")]
public int ClassificationId { get; set; }
}
Classification Model:
public class Classification
{
public int ClassificationId { get; set; }
public string Description { get; set; }
}
Create (Patient) View:
<div class="form-group">
#Html.LabelFor(model => model.ClassificationId, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.ClassificationId)*#
#Html.DropDownListFor(model => model.ClassificationId, (IEnumerable<SelectListItem>)ViewBag.Classifications, "Select Classification")
#Html.ValidationMessageFor(model => model.ClassificationId)
</div>
</div>
Edit (Patient) View:
<div class="form-group">
#Html.LabelFor(model => model.ClassificationId, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.ClassificationId)*#
#Html.DropDownListFor(model => model.ClassificationId,(IEnumerable<SelectListItem>)ViewBag.Classifications, "Select Classification")
#Html.ValidationMessageFor(model => model.ClassificationId)
</div>
</div>
Index (Patient) View:
<td>
#Html.DisplayFor(modelItem => item.ClassificationId)
</td>

You need to distinguish between the SelectListItem.Text (which is displayed in the dropdown) and the SelectListItem.Value (which is the value bound to your model)
Replacing the line in your controller defining ViewBag.Classifications with something like this:
ViewBag.Classifications = dbCC.Classifications
.Select(c => new SelectListItem { Value = c.ClassificationId, Text = c.Description })
.ToList();
ought to do it.

Related

Editing Objects and Related Objects in One View with ASP.Net MVC and Entity Frameworks

I am creating an application where a Note can be created and one to many Parts can be added to the note. (The application is for a tractor salvage yard where customers call for tractor parts). I know similar questions have been asked before. But I couldn't find anything very relevant to my situation with EF and all.
I am having a lot of difficulty with creating/editing a Note with its Parts in one view. I want to focus on editing for this question, though.
I have two simple CLR classes with a relation.
public class Note
{
public int ID { get; set; }
public string CustomerName { get; set; }
public string CustomerPhone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public string CreatedBy { get; set; }
public string AssignedTo { get; set; }
public virtual ICollection<Part> Parts { get; set; }
}
public class Part
{
public int PartID { get; set; }
public string PartNumber { get; set; }
public string Description { get; set; }
public int NoteID { get; set; }
public virtual Note Note { get; set; }
}
And the DbContext:
public class CallNoteContext : DbContext
{
public CallNoteContext() { }
public DbSet<Note> Notes { get; set; }
public DbSet<Part> Parts { get; set; }
}
My problem is binding the data from both entities to the edit view, accessing the data in the view for editing and saving the note and and multiple parts to the database in the httppost action.
I have tried a lot of things, but after reading a lot of articles, I keep coming back to this for the controller and view. To me it seems like this should work. But obviously I am missing something.
Here is the edit and post actions from my controller.
private CallNoteContext db = new CallNoteContext();
// GET: Note/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Note note = db.Notes.Find(id);
var model = new Note()
{
CustomerName = note.CustomerName,
CustomerPhone = note.CustomerPhone,
DateCreated = note.DateCreated,
DateUpdated = note.DateUpdated,
CreatedBy = note.CreatedBy,
AssignedTo = note.AssignedTo,
Parts = note.Parts
};
if (note == null)
{
return HttpNotFound();
}
return View(model);
}
// POST: Note/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,CustomerName,CustomerPhone,DateCreated,DateUpdated,CreatedBy,AssignedTo,Parts")] Note note)
{
if (ModelState.IsValid)
{
foreach(var p in note.Parts)
{
db.Entry(p).State = EntityState.Modified;
db.SaveChanges();
}
db.Entry(note).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(note);
}
When I try to make editors for p.PartNumber and p.Description in my view below, it breaks with the exception that it can't find these properties. I have a feeling that I am doing something wrong in the "get" action of the controller. But I am having a hard time figuring out what is wrong.
By the way, IntelliSense is saying No Issues Found for the controller.
Here is my Edit view.
#model CallNote.Models.Note
<head>
<script src="~/Scripts/jquery-3.4.1.js" type="text/javascript"></script>
</head>
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.CustomerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerPhone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CustomerPhone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerPhone, "", new { #class = "text-danger" })
</div>
</div>
#*There are editors here for all of the properties, but I didn't list them to save space.*#
#*The app always breaks when it gets to this foreach because it says it can't find p.PartNumber. What is wrong?
#foreach (var p in Model.Parts)
{
<div>
#*I also tried just using p.PartNumber, but it says p doesn't exist in current context.
#Html.EditorFor(p => p.PartNumber)
#Html.EditorFor(p => p.Description)
</div>
}
<div id="partInfo" style="display:none">
#Html.EditorFor(p => p.PartNumber)
#Html.EditorFor(p => p.Description)
</div>
<div id="btnWrapper">
<input id="btnAddPart" type="button" value="Add Part" />
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
#*The script below works, allowing you to add part editors*#
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script>
$(document).ready(function () {
$("#btnAddPart").click(function () {
var partinfo = $("#partInfo").html();
$("#partInfo").append(partinfo);
});
});
</script>
Also I am unsure if the httppost action will work. I have not been able to try it yet as I cannot get the Edit view to even load yet. So if you have any suggestions for that too, let me know.
I am just getting started with MVC, so a detailed answer would be super!
you have to include Parts in the Note
....
Note note = db.Notes
.Include(i=> i.Parts)
.FirstOrDefault(i=>i.ID==id);
if (note == null)
{
return HttpNotFound();
}
.....
and since you are using editor, replace foreach loop by for loop
#if( Model.Parts!=null && Model.Parts.Count >0)
{
#for (var i=0; i< Model.Parts.Count; i++)
{
<div id="partInfo" style="display:none">
#Html.EditorFor(model => model.Parts[i].PartNumber)
#Html.EditorFor(model => model.Parts[i].Description)
</div>
...... and so on for all properties
}
}
and remove bind from the action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Note note)
{
if (!ModelState.IsValid) return View(note);
var existedNote = db.Notes
.Include(i=> i.Parts)
.FirstOrDefault(i=>i.ID==note.ID);
if(existedNote!=null)
{
db.Entry(existedNote).CurrentValues.SetValues(note);
if(note.Parts!=null && note.Parts.Count > 0)
{
foreach( var part in note.Parts)
{
var existingPart = existingNote.Parts.FirstOrDefault(p => p.PartID == part.PartID);
if (existingPart == null)
{
existingNote.Parts.Add(part);
}
else
{
context.Entry(existingPart).CurrentValues.SetValues(part);
}
}
}
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(note);
}
````

Populating DropDownList in ASP.NET MVC

Following code is to create users. I have a user class, I need to create users here. But I have department id's on a person and that department id refers to another table in the database whose name is Department.
public ActionResult Create()
{
// disable lazy because of error it creates
_db.Configuration.LazyLoadingEnabled = false;
var data = _db.Departments.OrderBy(a => a.DepartmentId).ToList();
ViewData["DepartmentList"] = data;
return View();
}
Here is View:
#{
var departmentLists = ViewData["DepartmentList"]; // Cast the list
}
<div class="form-group">
#Html.LabelFor(model => model.Department, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.Department, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Department, "", new { #class = "text-danger" })
</div>
</div>
This model.department part is the where i lost. I need to list my department in order of the list, when user select, i want to select the id of the department.
Like this;
So I want the user to see
Department Name + SubDepartment name
and when they choose from the list, the chosen thing is
departmentid
so I can add in the database like that.
Here is my Create Post method:
public ActionResult Create([Bind(Include = "ID,LastName,FirstMidName,EnrollmentDate,Email,Department,Position,Active")] User user)
{
if (ModelState.IsValid)
{
_db.Users.Add(user);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Her is my User class;
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int DepartmentId { get; set; }
// Other fields removed for brevity
}
Here is Department class;
public class Department
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string SubDepartmentName { get; set; }
}
Write your Create GET method as follows:
public ActionResult Create()
{
// disable lazy because of error it creates
_db.Configuration.LazyLoadingEnabled = false;
var departmentList = _db.Departments.Select(d => new
{
d.DepartmentId,
DepartmentName = d.DepartmentName + " " + d.SubDepartmentName
}).OrderBy(a => a.DepartmentId).ToList();
ViewBag.DepartmentList = new SelectList(departmentList,"DepartmentId","DepartmentName");
return View();
}
Then in the view:
<div class="form-group">
#Html.LabelFor(model => model.DepartmentId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("DepartmentId", ViewBag.DepartmentList as SelectList, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DepartmentId, "", new { #class = "text-danger" })
</div>
</div>
Another problem is in your Create POST method. You are not allowing you DepartmentId to pass in your Bind include list. Please update you Create POST method as follows:
public ActionResult Create([Bind(Include = "ID,LastName,FirstMidName,EnrollmentDate,Email,DepartmentId,Position,Active")] User user)
{
if (ModelState.IsValid)
{
_db.Users.Add(user);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}

Edit in mvc4 didn't work

I want to edit this data in database and return new data
when i click on save button data doesn't change
Here is controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomPerformancePerformersModel customPerformancePerformersModel)
{
if (ModelState.IsValid)
{
int perfromanceId = Convert.ToInt32(TempData.Peek("CurrentPerformanceId"));
customPerformancePerformersModel.performanceObj = db.Performances.Where(x => x.PerformanceId == perfromanceId).FirstOrDefault();
db.Entry(customPerformancePerformersModel.performanceObj).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EventId = new SelectList(db.Events, "EventId", "Name", customPerformancePerformersModel.performanceObj.EventId);
ViewBag.VenueId = new SelectList(db.Venues, "VenueId", "Name", customPerformancePerformersModel.performanceObj.VenueId);
ViewBag.Performers = new SelectList(db.PerformerPerformances, "Performers", "Name", customPerformancePerformersModel.performanceObj.PerformerPerformances);
return View(customPerformancePerformersModel.performanceObj);
}
and here is the html:
<div class="form-group">
#Html.LabelFor(model => model.performanceObj.IsVisible, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.performanceObj.IsVisible)
#Html.ValidationMessageFor(model => model.performanceObj.IsVisible, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.performanceObj.IsFeatured, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.performanceObj.IsFeatured)
#Html.ValidationMessageFor(model => model.performanceObj.IsFeatured, "", new { #class = "text-danger" })
</div>
</div>
Try the following:
if (ModelState.IsValid)
{
int perfromanceId = Convert.ToInt32(TempData.Peek("CurrentPerformanceId"));
// There is no need to use Where. FirstOrDefault has an overload using predicates.
var savedPerformance = db.Performances.FirstOrDefault(x => x.PerformanceId == perfromanceId);
// If the performance couldn't be found, then you could add the error to the model state and return it to the view.
if(savedPerformance == null)
return View(customPerformancePerformersModel.performanceObj);
// Update properties from performance in database with new performance.
savedPerformance.someProperty = customPerformancePerformersModel.performanceObj.someProperty;
db.Performances.Attach(savedPerformance);
db.Entry(savedPerformance ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Ideally your code will look something like the following:
public ActionResult Edit(int performanceId)
{
var model = db.Performances.FirstOrDefault(m => m.PerformanceId == performanceId);
return View(model);
}
[HttpPost] //[HttpPatch] is technically correct, but most people I see tend to use only GET and POST actions.
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomPerformancePerformersModel model)
{
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
}
You're retrieving the object from the database and tracking it in your GET action, modifying it using your form, then marking it as modified in your update action. This is strictly if you're using the MVC pattern, and will look different (see below) if you're using separate data and view models. You'll likely run into trouble with this approach if your view doesn't have fields (hidden or not) for all properties on your model.
Using separate data and view models, you'd have something like this:
public ActionResult Edit(int performanceId)
{
var performance = db.Performances.FirstOrDefault(m => m.PerformanceId == performanceId);
var model = new PerformanceViewModel(performance); //In this constructor, copy properties from your data model to your view model
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PerformanceViewModel model)
{
var performance = db.Performances.FirstOrDefault(m => m.PerformanceId == model.PerformanceId);
model.Update(performance);
db.SaveChanges();
}
With a sample view model:
public class PerformanceViewModel
{
public PerformanceViewModel(CustomPerformanceePerformersModel model)
{
PerformanceId = model.performanceObj.PerformanceId;
IsVisible = model.performanceObj.IsVisible;
IsFeatured = model.performanceObj.IsFeatured;
}
public int PerformanceId { get; set; }
public bool IsVisible { get; set; }
public bool IsFeatured { get; set; }
public void Update(CustomPerformancePerformersModel model)
{
model.performanceObj.IsVisible = IsVisible;
model.performanceObj.IsFeatured = IsFeatured;
}
}
Here you're creating a separate object (view model) that holds only the necessary data for your view, then using the data from that object to update your data model. I prefer this because it takes the ability to effectively directly modify the database, and because you can do any necessary intermediate processing (casting strings to bools, et cetera) in the Update(Model) method.

both create and table in the same view

Im trying to join two tables and show a table from those joined results , as well as show a create form the same view
I just followed following questions answer
here these are the my model classes
public class CategoryViewModel
{
public AB_ProductTypeCategory categoryCreate { get; set; }
public IEnumerable<AB_ProductTypeCategory> categoryList { get; set; }
}
public partial class AB_ProductTypeCategory
{
public string ProductCategoryID { get; set; }
public string ProductTypeID { get; set; }
public string ProductCategoryNameEn { get; set; }
}
these are the controller methods
Join LINQ query to get the list
[HttpGet]
public ViewResult ProductCategory_List()
{
var catagorylist = from cat in db.AB_ProductTypeCategory
join typ in db.AB_ProductType on cat.ProductTypeID equals typ.ProductTypeID
select new AB_ProductTypeCategory
{
ProductCategoryID = cat.ProductCategoryID,
ProductCategoryNameEn = cat.ProductCategoryNameEn,
ProductTypeID= typ.ProductTypeID,
};
return View(catagorylist);
this is create controller method
[HttpGet]
public ActionResult ProductCategory_Create()
{
Product_Type_DropDownListEn();
Product_Type_DropDownListAr();
return View();
}
[HttpPost]
public ActionResult ProductCategory_Create(AB_ProductTypeCategory product_category)
{
Product_Type_DropDownListEn(product_category.ProductTypeID);
Product_Type_DropDownListAr(product_category.ProductTypeID);
if (ModelState.IsValid)
{
..
}
return View(product_category);
}
this is List viewpage "ProductCategory_List"
#model IEnumerable<project_name.Models.AB_ProductTypeCategory>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ProductCategoryID)
</th>
...
this is page Im trying to show list view and create view
#model project_name.Models.AB_ProductTypeCategory
#{
}
#{Html.RenderAction("ProductCategory_List", "Home");}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create New Product Category</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductCategoryID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductCategoryID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductCategoryID, "", new { #class = "text-danger" })
</div>
</div>
.....

Why i failed to get DropDownList value on submit event

In my MVC4 project I failed to get my DropDownList data on edit controller.
My UI syntax is bellow:
<div class="form-group">
#Html.HiddenFor(model => model.School.SchoolID)
#Html.LabelFor(model => model.School.SchoolName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.School.SchoolName)
#Html.ValidationMessageFor(model => model.School.SchoolName)
</div>
</div>
<div class="form-group">
#Html.HiddenFor(model => model.StudentCLass.ID)
#Html.LabelFor(model => model.StudentCLass.ClassName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StudentCLass.ID, #ViewBag.StudentCLassList as SelectList,"Select Class")
#Html.ValidationMessageFor(model => model.StudentCLass.ID)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
To fill the DropDownList I use bellow syntax:
public ActionResult Edit(int Id)
{
using (DB = new StudentContext())
{
var result = DB.Students.FirstOrDefault(c => c.ID == Id);
ViewBag.StudentCLassList = new SelectList(DB.StudentClasses
.Select(sc => new ViewModelClass
{
ID = sc.ID,
ClassName = sc.ClassName
}).ToList(), "ID", "ClassName");
return View(StudentInfo(result));
}
}
After click the submit button I can not get DropDownList value on my controller action.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{
var tempResult = student.StudentCLass.ID;
//return RedirectToAction("Index");
// return View(student);
}
Model structure
public partial class StudentClass
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public StudentClass()
{
Students = new HashSet<Student>();
}
public int ID { get; set; }
[StringLength(100)]
public string ClassName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Student> Students { get; set; }
}
MVC Doen't post the DropDown list back to the Controller, You will have to populate dropdown list again in POST method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{
var tempResult = student.StudentCLass.ID;
ViewBag.StudentCLassList = new SelectList(DB.StudentClasses
.Select(sc => new ViewModelClass
{
ID = sc.ID,
ClassName = sc.ClassName
}).ToList(), "ID", "ClassName");
return RedirectToAction("Index");
}
You could write the Dropdown list code in a function, if you don't want to read this dropdown list from DB evertime you can save it to Session[]:
public void PopulateDropDownList(){
var items = Session["MyDropDown"] != null ? (SelectList)Session["MyDropDown"] : null;
if(items ! null) {ViewBag.StudentCLassList; return;}
items = new SelectList(DB.StudentClasses
.Select(sc => new ViewModelClass
{
ID = sc.ID,
ClassName = sc.ClassName
}).ToList(), "ID", "ClassName");
Session["MyDropDown"] = ViewBag.StudentCLassList = items;
}
Note: If you save the DropDown list in Session, you don't have write it to ViewBag, but you can access it directly in View.
And call this method in Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{
var tempResult = student.StudentCLass.ID;
PopulateDropDownList();
return RedirectToAction("Index");
}
EDIT
I don't understand you are saying that you want the DropDown to be selected but you are Redirecting to `Index'.
If you do:
return View(student);
Instead of
return RedirectToAction("Index");
return RedirectToAction("Index"); will redirect you to Index page, refreshing your webpage.
EDIT 2:
I just noticed you have
#Html.HiddenFor(model => model.StudentCLass.ID)
MVC is posting the Value from this Hidden Back to the Controller. Try removing this,
The thing is that you have two controls with the same id
#Html.DropDownListFor(model => model.StudentCLass.ID
AND
#Html.HiddenFor(model => model.StudentCLass.ID)
I think you want something like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{
if (ModelState.IsValid)
{
// save changes and redirect
return RedirectToAction("Index");
}
else
{
using (DB = new StudentContext())
{
ViewBag.StudentCLassList = new SelectList(DB.StudentClasses.ToList(), "ID", "ClassName");
}
return View(student);
}
}
The framework will take care of preserving selected values across requests.

Categories

Resources