I made a dropdown list for me to assign Admin Roles to certain users when I create them:
But they don't assign themselves properly, as you can see here:
It happens because of this line Value = "Administrator LVL2"
. My question is: How do i assign it to my model like I've done for assigning last names:
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
Views\User\Create.cshtml
<div class="editor-label">
@{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Administrator LVL1",
Value = model => model.AdminRole, <-- THIS IS WRONG
});
listItems.Add(new SelectListItem
{
Text = "Administrator LVL2",
Value = "Administrator LVL2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Administrator LVL3",
Value = "Administrator LVL3"
});
}
@Html.DropDownListFor(model => model.AdminRole, listItems, "-- Select Admin Role --")
</div>
UserController.cs
public class UserController : Controller
{
private IssueContext db = new IssueContext();
//
// GET: /User/
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var users = from s in db.Users
select s;
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
|| s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
users = users.OrderByDescending(s => s.LastName);
break;
case "Date":
users = users.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
users = users.OrderByDescending(s => s.EnrollmentDate);
break;
default: // Name ascending
users = users.OrderBy(s => s.LastName);
break;
}
int pageSize = 5;
int pageNumber = (page ?? 1);
return View(users.ToPagedList(pageNumber, pageSize));
}
//
// GET: /User/Details/5
public ActionResult Details(int id = 0)
{
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
//
// GET: /User/Create
public ActionResult Create()
{
return View();
}
//
// POST: /User/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
[Bind(Include = "LastName, FirstMidName, EnrollmentDate, DepartmentID, DepotID")]
User user)
{
try
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(user);
}
//
// GET: /User/Edit/5
public ActionResult Edit(int id = 0)
{
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
//
// POST: /User/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(
[Bind(Include = "UserID, LastName, FirstMidName, EnrollmentDate, DepartmentID, DepotID")]
User user)
{
try
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(user);
}
//
// GET: /User/Delete/5
//This code accepts an optional Boolean parameter that indicates whether it was called after a failure to save changes.
//This parameter is false when the HttpGet Delete method is called without a previous failure. When it is called by the
//HttpPost Delete method in response to a database update error, the parameter is true and an error message is passed to the view.
public ActionResult Delete(bool? saveChangesError = false, int id = 0)
{
if (saveChangesError.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
//
// POST: /User/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
try
{
User user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
}
catch (DataException/* dex */)
{
// uncomment dex and log error.
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
return RedirectToAction("Index");
}
//To make sure that database connections are properly closed and the resources they hold freed up, you should see to it that the context instance is disposed.
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
How my classes are mapped:
User to Admin is 1 to 0..1 (I can assign some users with admin status but I don't want every user to have it)
Admin to Ticket is 1 to Many(You can only assign 1 admin(to fix the issue) to a ticket)
User to Ticket is 1 to many (One user can create multiple tickets)
User.cs
public class User
{
public int UserID { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
public string FullName
{
get { return LastName + ", " + FirstMidName; }
}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int? AdministratorID { get; set; }
[ForeignKey("AdministratorID")]
public virtual Administrator Administrator { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
Ticket.cs
public class Ticket
{
public int TicketID { get; set; }
public string Issue { get; set; }
[DisplayFormat(NullDisplayText = "No Priority")]
public Priority? Priority { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public int CategoryID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
public int AdministratorID { get; set; }
[ForeignKey("AdministratorID")]
public virtual Administrator Administrator { get; set; }
}
Administrator.cs
public class Administrator
{
public int AdministratorID { get; set; }
public string AdministratorTitle { get; set; }
public virtual ICollection<User> Users { get; set; }
}