I am working on an asp.net mvc 4 application where I am trying to add delete a user functionality for an admin where I should be able to select a user from dropdown list and delete him.
I was able to delete a user by manually typing in a username in a textbox but I wanted to prepopulate a drop down with list of all users.
I started off the functionality using a textbox
Controller
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult DeleteUser(UserProfile model)
{
if (ModelState.IsValid)
{
/
try
{
if (model.UserName == null)
{
TempData["ErrorMessage"] = "Username required.";
return RedirectToAction("Register", "Account");
}
else
{
var user = Membership.GetUser(model.UserName);
if (user == null)
{
TempData["ErrorMessage"] = "User Does Not exist.";
return RedirectToAction("Register", "Account");
}
else
{
Membership.DeleteUser(model.UserName);
}
return RedirectToAction("Register", "Account");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
return View(model);
}
DeleteUser.cshtml
@model WhiteBoardApp.Models.UserProfile
@using (Html.BeginForm("DeleteUser", "Account"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<div class="container-fluid">
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
<span style="color:red;">@TempData["ErrorMessage"]</span>
</li>
</ol>
<input type="submit" value="Delete User" />
</div>
</fieldset>
}
May I know how I can replace username textbox with a dropdon list with all the usernames?
Add ExistingUsers property of type IEnumerable< SelectListItem > in UserProfile class.
Query the database to populate ExistingUsers with the list of users.
Replace '@Html.TextBoxFor(m => m.UserName)' with '@Html. DropDownListFor(m => m.UserName, Model.ExistingUsers)'.