I am having problem understanding as to why my model is not updating when I select a new value from my dropdownlist control?
Here is my model
public class UserViewModel
{
public Users users { get; set; }
public IEnumerable<SelectListItem> UserRoles { get; set; }
}
Controller
//GET
public ActionResult Edit(int id)
{
var vm = new UserViewModel();
vm.users = repository.GetById(id);
vm.UserRoles = db.UserRoles.Select(
x => new SelectListItem
{
Selected = true,
Text = x.UserRoleName,
Value = x.UserRoleID.ToString()
}
);
if (vm == null)
{
return HttpNotFound();
}
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserViewModel model)
{
if(ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
And finally my View
<div class="form-group">
<label class="control-label col-md-2">User Role</label>
<div class="col-md-10">
#Html.HiddenFor(model => model.users.UserRoleID)
#Html.DropDownListFor(model => model.UserRoles, (IList<SelectListItem>)ViewBag.UserRoles, "-- Select One --", new { #class = "form-control" })
</div>
</div>
I have stepped through the code and in the Collection can see UserRoles in the collection but I am not sure if I am passing the value correctly?
UPDATE
I have updated my POST method for updating the model
public ActionResult Edit(int id, UserViewModel model)
{
var user = repository.GetById(id);
if (ModelState.IsValid)
{
if (user != null)
{
user.Username = model.users.Username;
user.Forename = model.users.Forename;
user.Lastname = model.users.Lastname;
user.Email = model.users.Email;
user.Status = model.users.Status;
user.UserRoleID = Convert.ToInt32(model.UserRoles);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View();
}
}
return View();
}
However on Submit it is giving me a Null reference exception on the dropdownlist as shown below? Now sure why?
(IList<SelectListItem>)ViewBag.UserRoles
you data exist in vm.UserRoles lists not in ViewBag.UserRoles but you are attaching list using Viewbag
ViewBag.UserRoles = db.UserRoles.Select(
x => new SelectListItem
{
Selected = true,
Text = x.UserRoleName,
Value = x.UserRoleID.ToString()
}
assign the list to the view model then you will get access to the list from the page
Finally solved the issue. Created a new property inside my ViewModel which will store the selected value for When posting back to Controller
public class UserViewModel
{
public Users users { get; set; }
public IEnumerable<SelectListItem> UserRoles { get; set; }
public string selectedRole { get; set; }
}
Made change to my View to include the new property
#Html.DropDownListFor(model => model.selectedRole, Model.UserRoles, "-- Select One --", new { #class = "form-control" })
and on Post I pass the selected value
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, UserViewModel model)
{
var user = repository.GetById(id);
if (ModelState.IsValid)
{
if (user != null)
{
user.Username = model.users.Username;
user.Forename = model.users.Forename;
user.Lastname = model.users.Lastname;
user.Email = model.users.Email;
user.Status = model.users.Status;
user.UserRoleID = Convert.ToInt32(model.selectedRole);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View();
}
return View();
}
I think the wrong code is in the View:
<div class="col-md-10">
#Html.HiddenFor(model => model.users.UserRoleID)
#Html.DropDownListFor(model => model.UserRoles (IList<SelectListItem>)ViewBag.UserRoles, "-- Select One --", new { #class = "form-control" })
</div>
The next code should work:
<div class="col-md-10">
#Html.DropDownListFor(model => model.users.UserRolesID, new SelectList(Model.UserRoles, "Id", "Name"), new { #class = "form-control" })
</div>
where there is a direct binding between model.users.UserRolesID and the list containing user roles (I suppose that UserRoles is done as id,description)
Related
I have a people controller for user management and I'm trying to figure out how to get the dropdown choice when the user submits from the edit page. Whenever I hit submit on the page, none of the values from the view model seem to carry through to the post. I can't get the value they chose from the drop down to set the role.
See view model below:
public class PersonViewModel
{
public int PersonId { get; set; }
[Display(Name = "Full Name")]
public string FullName { get; set; }
public string Email { get; set; }
[Display(Name = "Current Role")]
public string SetRole { get; set; }
public List<RoleListViewModel> Roles { get; set; }
}
See controller edit functions below:
// GET: People/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.people.Find(id);
if (person == null)
{
return HttpNotFound();
}
PersonViewModel pvm = new PersonViewModel();
List<IdentityRole> roles = adb.Roles.ToList();
var rlvm = new List<RoleListViewModel>();
roles.ForEach(x => rlvm.Add(new RoleListViewModel { RoleId = x.Id, RoleName = x.Name }));
pvm.PersonId = person.PersonId;
pvm.FullName = person.FirstName + " " + person.LastName;
pvm.Email = person.Email;
pvm.Roles = rlvm;
ViewBag.RoleList = new SelectList(rlvm, "RoleName", "RoleName", person.CurrentRole);
return View(pvm);
}
// POST: People/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonViewModel pvm)
{
if (ModelState.IsValid)
{
db.Entry(pvm).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
var usr = new AccountController();
var pers = db.people.Where(x => x.PersonId == pvm.PersonId).FirstOrDefault();
usr.UserManager.AddToRoleAsync(pers.NetId, /* their choice should go here but how? */);
db.SaveChanges();
return View(pvm);
}
Here is the cshtml:
<div class="form-group">
#Html.LabelFor(model => model.Roles, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="form-control-static">
#Html.DropDownList("RoleList", null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Roles, "", new { #class = "text-danger" })
</div>
</div>
Make a variable in your View Model to store the selected value and then in the view use
#Html.DropDownListFor(m => m.SelectedRoleVariable, RolesSelectList, new { #class = "form-control" });
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.
What I'm trying to do...
I am trying to get a newly added item to display in a cascading dropdownlist.
Overview...
The first dropdownlist (I'll call it ddlCategory) is for selecting a Category of electrical devices (ie. Appliances, Audio-Visual, Lighting, etc.). The second dropdownlist (I'll call ddlElecDev) is populated with the devices which are filtered by the selected Category. If the device isn't listed in ddlElecDev then the user can click a link to add a new one. After saving the newly added electrical device, the user is redirected back to the original page with the electrical device id as a parameter.
All the above seems to work fine. However, when the user is redirected to the first page, not only is the newly added electrical device not selected in ddlElecDev, but it doesn't even appear in the list. Strangely, if I refresh the page, it is automatically selected.
Can anyone explain to me how to get the newly added device to be selected without having to refresh the page?
Here's the markup for selecting the category and electrical device:
<div class="form-group">
#Html.LabelFor(model => model.SelectedCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedCategory, Model.Categories, "Select a Category", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedCategory, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ElectricalDeviceID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CascadingDropDownListFor(
expression: model => model.ElectricalDeviceID,
triggeredByProperty: model => model.SelectedCategory,
url: Url.Action("GetElectricalDevices", "ElectricalDeviceConfigurations"),
ajaxActionParamName: "categoryId",
optionLabel: "Select an Electrical Device",
disabledWhenParrentNotSelected: false,
htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ElectricalDeviceID, "", new { #class = "text-danger" })
#Html.ActionLink("Not Listed? Add a new Electrical Device", "AddNew", "ElectricalDevices", new { returnUrl = string.Format("/ElectricalDeviceConfigurations/AddConfiguration?eventVendorId={0}", Model.EventVendorID) }, null)
</div>
</div>
The documentation for the Cascading DropDownList Helper can be found at
https://github.com/alexanderar/Mvc.CascadeDropDown
Here's the Controller method for selecting the Electrical Device:
public ActionResult AddConfiguration(int? eventVendorId, int? newElecDev)
{
(Some code removed for brevity)
var selectedCategoryId = db.ElectricalDeviceCategoryLookups.Where(cat => cat.Category == Enums.ElectricalDeviceCategory.All).FirstOrDefault().ID;
var electricalDeviceID = (newElecDev.HasValue) ? newElecDev : null;
return View(new ElecDevConfigSelectionViewModel { EventVendorID = eventVendorId, EventVendor = eventVendor, Categories = GetCategories(), SelectedCategory = selectedCategoryId, ElectricalDeviceID = electricalDeviceID });
}
Here's the controller methods for populating the Categories and the Electrical Devices:
private List<SelectListItem> GetCategories()
{
var categories = new List<SelectListItem>();
db.ElectricalDeviceCategoryLookups.OrderBy(c => c.Description).ToList().ForEach(item => categories.Add(new SelectListItem { Text = item.Description, Value = item.ID.ToString() } ));
return categories;
}
public ActionResult GetElectricalDevices(int? categoryId)
{
if (categoryId.HasValue)
{
var selCategory = db.ElectricalDeviceCategoryLookups.Where(cat => cat.ID == categoryId).FirstOrDefault().Category;
var elecDevicesSelectList = new List<SelectListItem>();
var elecDevices = (selCategory == Enums.ElectricalDeviceCategory.All) ? db.ElectricalDevices.OrderBy(ed => ed.Name).ToList() : db.ElectricalDevices.Where(ed => ed.Category == selCategory).OrderBy(ed => ed.Name).ToList();
elecDevices.ForEach(ed => elecDevicesSelectList.Add(new SelectListItem { Text = ed.Name, Value = ed.ID.ToString() }));
return Json(elecDevicesSelectList, JsonRequestBehavior.AllowGet);
}
return null;
}
Here's the View Model:
public class ElecDevConfigSelectionViewModel
{
public int? EventVendorID { get; set; }
public EventVendor EventVendor { get; set; }
[Display(Name = "Category")]
public int SelectedCategory { get; set; }
public IList<SelectListItem> Categories { get; set; }
[Display(Name = "Electrical Device")]
public int? ElectricalDeviceID { get; set; }
}
Here's the controller methods for adding a new electrical device:
// GET: ElectricalDevices/AddNew
public ActionResult AddNew(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
var selectedCategoryId = db.ElectricalDeviceCategoryLookups.FirstOrDefault().ID;
return View(new AddNewElectricalDeviceViewModel { ReturnUrl = returnUrl, Categories = GetCategories(), SelectedCategory = null });
}
// POST: ElectricalDevices/AddNew
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddNew(AddNewElectricalDeviceViewModel model)
{
if (ModelState.IsValid)
{
var selectedCategory = db.ElectricalDeviceCategoryLookups.Find(model.SelectedCategory);
var electricalDevice = new ElectricalDevice
{
Name = model.ElectricalDevice.Name,
Description = model.ElectricalDevice.Description,
Category = selectedCategory.Category,
Wattage = model.ElectricalDevice.Wattage
};
db.ElectricalDevices.Add(electricalDevice);
db.SaveChanges();
var returnUrl = string.Format("{0}&newElecDev={1}", model.ReturnUrl, electricalDevice.ID);
return RedirectToLocal(returnUrl);
}
return View();
}
Here's the View Model for adding a new electrical device:
public class AddNewElectricalDeviceViewModel
{
public string ReturnUrl { get; set; }
[Display(Name = "Category")]
public int? SelectedCategory { get; set; }
public IList<SelectListItem> Categories { get; set; }
public ElectricalDevice ElectricalDevice { get; set; }
}
The error occurs when i tried to Submit/Post the data... could someone please help i tried every post but they are not helping me. I am new to mvc... any help will be granted
here is my code...
public ActionResult Create()
{
UserProfileCreateViewModel model = new UserProfileCreateViewModel();
model.Gender = _GenderRepository.GetAll()
.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.DESCRIPTION
});
return View(model);
}
[HttpPost]
public ActionResult Create(UserProfileCreateViewModel model)
{
if (ModelState.IsValid)
{
UserProfile user = new UserProfile();
user.GENDER_ID = model.GenderID;
_UserProfileRepository.Add(user);
_UserProfileRepository.Save();
return RedirectToAction("Index", "Home");
}
return View(model);
}
View
<div class="form-group">
#Html.LabelFor(model => model.GenderID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.GenderID, Model.Gender, "Select from List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GenderID, string.Empty, new { #class = "text-danger" })
</div>
</div>
Model
public class UserProfileCreateViewModel
{
[Required(ErrorMessage="{0} is required")]
[Display(Name="Gender")]
public int GenderID { get; set; }
public IEnumerable<SelectListItem> Gender { get; set; }
}
InvalidOperationException: The ViewData item that has the key 'GenderID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Here i have tried this....
// POST: /UserProfile/Create/
[HttpPost]
public ActionResult Create(UserProfileCreateViewModel model)
{
if (ModelState.IsValid)
{
UserProfile user = new UserProfile();
user.GENDER_ID = model.GenderID;
_UserProfileRepository.Add(user);
_UserProfileRepository.Save();
return RedirectToAction("Index", "Home");
}
model.Gender = _GenderRepository.GetAll().Select(x =>
new SelectListItem
{
Value = x.ID.ToString(),
Text = x.DESCRIPTION
});
return View(model);
}
The error means that the value of Model.Gender is null (and as a result the DropDownListFor() method expects that the first parameter is IEnumerable<SelectListItem>.
In your case, when you submit the form and ModelState is invalid, you return the view and have not assigned a value to Model.Gender (hence it is null and the excption is thrown.
Ensure that you re-assign the value of Model.Gender in the POST method (just as you did in the GET method) before you return the view.
It could be a problem between the "Gender":
[Display(Name="Gender")]
public int GenderID { get; set; }
public IEnumerable<SelectListItem> Gender { get; set; }
If I remember well, MVC attempts to map the fields automatically. Try renaming the (Name="Gender") in (Name="GenderID") or IEnumerable<SelectListItem> Gender in IEnumerable<SelectListItem> GenderEnumeration
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.