Related
AdminBlog is my controllers name.
Blog is a table in my database.
Foto is a column in the table.
when i saved the form, Foto column value become System.Web.HttpPostedFileWrapper. But others column's values are getting correct values. Also the image does not upload to BlogFoto file
Here is my model codes:
public partial class Blog
{
public int BlogID { get; set; }
public string BlogBaslik { get; set; }
[UIHint("tinymce_full")][AllowHtml]
public string BlogIcerik { get; set; }
public string Foto { get; set; }
public Nullable<int> BlogOkunmaSayisi { get; set; }
public Nullable<int> BlogOkunmaSuresi { get; set; }
public Nullable<System.DateTime> BlogTarih { get; set; }
}
and view codes:
#using (Html.BeginForm("Create", "AdminBlog",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Yeni Blog Oluştur</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BlogBaslik, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BlogBaslik, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BlogBaslik, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BlogIcerik, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BlogIcerik, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BlogIcerik, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="Foto" class="form-control" />
#Html.ValidationMessageFor(model => model.Foto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BlogOkunmaSuresi, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BlogOkunmaSuresi, new { htmlAttributes = new { #class = "form-control", #placeholder = "DK cinsinden giriniz" } })
#Html.ValidationMessageFor(model => model.BlogOkunmaSuresi, "", new { #class = "text-danger" })
</div>
</div>
and controllers:
[HttpPost]
public ActionResult Create(Blog blog, HttpPostedFile Foto)
{
try
{
if (Foto != null)
{
WebImage webImage = new WebImage(Foto.InputStream);
string newfoto = Path.GetFileNameWithoutExtension(Foto.FileName) + "-" + Guid.NewGuid() + Path.GetExtension(Foto.FileName);
var filePath = "/Uploads/BlogFoto" + newfoto;
webImage.Save(Server.MapPath(filePath));
blog.Foto = filePath;
}
blog.BlogOkunmaSayisi = 0;
blog.BlogTarih = DateTime.Now;
db.Blogs.Add(blog);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
change Blog to this :
public partial class Blog
{
//...............................
//...............................
public HttpPostedFileBase FotoFile { get; set; }
}
this code
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="Foto" class="form-control" />
#Html.ValidationMessageFor(model => model.Foto, "", new { #class = "text-danger" })
</div>
</div>
change to this :
<div class="form-group">
#Html.LabelFor(model => model.FotoFile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.FotoFile, new { type = "file", #class = "form-control" })
#Html.ValidationMessageFor(model => model.FotoFile, null, new { #class = "text-danger" })
</div>
</div>
and change controllert to this :
[HttpPost]
public ActionResult Create(Blog blog)
{
try
{
if (blog.FotoFile != null)
{
WebImage webImage = new WebImage(blog.FotoFile.InputStream);
string newfoto = Path.GetFileNameWithoutExtension(blog.FotoFile.FileName) + "-" + Guid.NewGuid() + Path.GetExtension(blog.FotoFile.FileName);
var filePath = "/Uploads/BlogFoto" + newfoto;
webImage.Save(Server.MapPath(filePath));
blog.Foto = filePath;
}
//..................................................................
//..................................................................
}
catch
{
return View();
}
}
I have a quick question I am updating my user and there role and my modelstate.isvalid is failing. So the user does not get updated in the database. I don’t have anything [required] that isn’t being entered in a textbox even when I try to enter all fields it still fails. Not sure why.
Here is my data model, my controller action for editing / updating a user and there role and also here is my view with all the controls for inside the view.
Im realy not sure why my modelstate isnt valid i'm not doing anything complicated its just a simple U in CRUD and the action controller isnt validiting the model.
public class UpdateUserViewModel
{
public string UserId { get; set; }
[Display(Name = "User ID")]
public string IdShortened { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Username")]
public string UserName { get; set; }
[Display(Name = "Your Name")]
public string Name { get; set; }
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[DataType(DataType.DateTime),
DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
[Display(Name = "Birthday")]
public DateTime Birthday { get; set; }
[Display(Name = "Date Created")]
public DateTime? DateCreated { get; set; }
[Required]
[Display(Name = "User Roles")]
public string UserRoles { get; set; }
}
public async Task<ActionResult> EditSuperAdmin(string id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = await manager.FindByIdAsync(id);
if(user == null)
{
return HttpNotFound();
}
var userRoles = await manager.GetRolesAsync(user.Id);
ViewBag.Roles = new SelectList(
context.Roles.ToList(), "Name", "Name");
//new SelectList(context.Roles.Where(u =>
//!u.Name.Contains("SuperAdmin")).ToList(), "Name", "Name");
return View(new UpdateUserViewModel()
{
UserId = user.Id,
IdShortened = user.Id.Substring(0, 10),
Email = user.Email,
UserName = user.UserName,
Name = user.Name,
PhoneNumber = user.PhoneNumber,
Birthday = user.Birthday,
DateCreated = user.DateCreated,
UserRoles = manager.GetRoles(user.Id).FirstOrDefault()
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditSuperAdmin([Bind]UpdateUserViewModel model)
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
if (ModelState.IsValid)
{
var user = manager.FindById(model.UserId);
if (user == null)
{
return HttpNotFound();
}
user.Email = model.Email;
user.UserName = model.UserName;
user.Name = model.Name;
user.PhoneNumber = model.PhoneNumber;
user.Birthday = model.Birthday;
user.DateCreated = Convert.ToDateTime(model.DateCreated);
var roleResult =
manager.AddToRole(user.Id, model.UserRoles);
if (!roleResult.Succeeded)
{
TempData["ErrorRole"] = "Error adding User Role";
return RedirectToAction("Dashboard");
}
manager.Update(user);
context.SaveChanges();
TempData["Success"] = "User Updated Successfully";
return RedirectToAction("GetAllUsers", "SuperAdmin");
}
TempData["Error"] = "User Update Failed";
return RedirectToAction("Dashboard");
} #model MVC_TimeSh.Models.UpdateUserViewModel
#{
ViewData["Title"] = "Update User";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="text-center">
#if (User.IsInRole("SuperAdmin"))
{
<h2>Update Super Administrator</h2>
}
else
{
<h3>Update | Edit User Account</h3>
}
</div>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(m => m.UserId)
<div class="form-group">
#Html.LabelFor(model => model.IdShortened,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IdShortened, new { htmlAttributes =
new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.IdShortened, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes =
new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PhoneNumber,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PhoneNumber,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PhoneNumber, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Birthday,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Birthday,
new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.Birthday, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateCreated,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateCreated, new { htmlAttributes =
new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.DateCreated, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserRoles,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("UserRoles", (SelectList)ViewBag.Roles, "-- SELECT --")
#*new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.UserRoles, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
</div>
Sorry don't have 50 reputations can't comment.
As Chetan said debug and check the ModelState errors and check if UserRoles property is the issue.
it will be fine if you go with entity framework. Everything works fine there.
I'm trying to learn ASP.net MVC. I'm using the pre-populated asp.net project that has a fake website within it to start. I have a form, and on submit, I want to put the values into a table in my database. I would also like to add functionality that if the email already exists in the database, I redirect them to another page.
I've added my own view, model, and controller.
Here's my databases (Side question: should I just put the table I created into DefaultConnection instead of Users.mdf?)
My Model:
public class RegisterLoyaltyViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
public string Phone { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public string optSweepstakes { get; set; }
public string optEmails { get; set; }
}
My relevant controller code:
// POST: /Account/RegisterLoyalty
[HttpPost]
[AllowAnonymous]
public void RegisterLoyalty(RegisterLoyaltyViewModel model)
{
//Currently nothing here
}
I think what I need to do is hit the database inside the controller. I need to check if email already exists in the table, and if it does, redirect to page x. If email does not exist, simply submit the model to the database, and redirect to page y.
You need a data layer implementation to hit the database, there are various ways of doing it one of which is using Entity Framework, have a look at here to get some ideas, or alternatively you can use ADO.NET to connect to the database.
Create a controller action to GET the RegisterLoyalty view. That view contains a the RegisterLoyalty form. Have the form POST to the RegisterLoyalty action. Then you can perform your logic and add the model to the db if necessary.
//
// GET: /Account/RegisterLoyalty
[AllowAnonymous]
public ActionResult RegisterLoyalty()
{
return View();
}
//
// POST: /Account/RegisterLoyalty
[HttpPost]
[AllowAnonymous]
public ActionResult RegisterLoyalty(RegisterLoyaltyViewModel model)
{
var db = new AccountLoyaltyDbContext();
var emailExists = db.Loyalties.Any(x => x.EmailAddress == model.EmailAddress);
if (emailExists)
{
return RedirectToAction("X");
}
db.Loyalties.Add(model);
db.SaveChanges();
return RedirectToAction("Y");
}
//
// GET: /Account/X
[AllowAnonymous]
public ActionResult X()
{
return View();
}
//
// GET: /Account/Y
[AllowAnonymous]
public ActionResult Y()
{
return View();
}
RegisterLoyalty.cshtml
#model UserLoyalty.Models.RegisterLoyaltyViewModel
#{
ViewBag.Title = "RegisterLoyalty";
}
<h2>RegisterLoyalty</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>RegisterLoyaltyViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SecurityQuestion, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SecurityQuestion, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SecurityQuestion, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SecurityAnswer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SecurityAnswer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SecurityAnswer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.optSweepstakes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.optSweepstakes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.optSweepstakes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.optEmails, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.optEmails, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.optEmails, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
So here is some code:
Controller
[HttpGet]
public ActionResult GetSettings()
{
var save = new SettingsSaver();
var dto = save.GetSettings();
var model = new SettingsModel
{
Password = dto.Password,
Port = dto.Port,
Username = dto.Username,
Enabled = dto.Enabled,
Id = dto.Id,
IpAddress = dto.IpAddress,
};
return View(model);
}
[HttpPost]
public ActionResult GetSettings(SettingsModel viewModel)
{
if (ModelState.IsValid)
{
var dto = new SettingsDto
{
IpAddress = viewModel.IpAddress,
Password = viewModel.Password,
Port = viewModel.Port,
Username = viewModel.Username,
Enabled = viewModel.Enabled,
Id = viewModel.Id
};
var save = new SettingsSaver();
var result = save.SaveSettings(dto); //Saves correctly and updates in DB
if (result)
{
return View(); // Returns this
}
return View("Error");
}
return View("Error");
}
View (Default Edit View)
#model Dash.UI.Models.Settings.SettingsModel
#{
ViewBag.Title = "Settings";
}
<h2>Settings</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Settings</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Enabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Enabled)
#Html.ValidationMessageFor(model => model.Enabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IpAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IpAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IpAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Port, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Port, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Port, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</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>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
So, what the problem is when I update the model and POST to GetSettings it all works correctly, updates in the db etc. but on the return View() it does not hit the GetSettings() action method, but it returns the view with all of the model filled in except the password.
Model
public class SettingsModel : BaseSettingsViewModel // Base contains ID and Enabled properties with no data annotations
{
[Required]
[DataType(DataType.Text)]
[DisplayName("IP Address")]
public string IpAddress { get; set; }
[Required]
[DisplayName("Port")]
public int Port { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("Username")]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
}
Any advise/guidance would be much appreciated.
Upon returning the same view from a POST, the ModelState will fill in the controls (apart from the password fields) from the posted values.
So you need a Post-Redirect-Get pattern:
if (result)
{
return RedirectToAction("GetSettings");
}
I have a model:
public class DbUserRole
{
public int UserRoleId { get; set; }
public string UserRole { get; set; }
}
public class DbUserRoles
{
public List<DbUserRole> GetRoles()
{
BugnetReports RoleDropDown = new BugnetReports();
List<DbUserRole> Roles = new List<DbUserRole>();
DataSet table = RoleDropDown.userRoleDropDown();
foreach (DataRow item in table.Tables[0].Rows)
{
DbUserRole ur = new DbUserRole();
ur.UserRole = Convert.ToString(item["UserRoleName"]);
ur.UserRoleId = Convert.ToInt32(item["UserRoleID"]);
Roles.Add(ur);
}
return Roles;
}
}
And here is the Controller that loads the view:
//
// GET: /Admin/AddNewUser
public ActionResult AddNewUser()
{
DbUserRoles Roles = new DbUserRoles();
return View(Roles.GetRoles());
}
I can get the items in the list to display using a #foreach loop as shown below:
#foreach (var item in Model)
{
<tr>
<td>
#item.UserRoleId
</td>
<td>
#item.UserRole
</td>
</tr>
}
But how do I populate a dropdownlist with the model that is passed through, I have tried
#Html.DropDownListFor(x => x.UserRole)
but I'm having no luck.
You can separate out your business logic into a viewmodel, so your view has cleaner separation.
First create a viewmodel to store the Id the user will select along with a list of items that will appear in the DropDown.
ViewModel:
public class UserRoleViewModel
{
// Display Attribute will appear in the Html.LabelFor
[Display(Name = "User Role")]
public int SelectedUserRoleId { get; set; }
public IEnumerable<SelectListItem> UserRoles { get; set; }
}
References:
DisplayAttribute
Inside the controller create a method to get your UserRole list and transform it into the form that will be presented in the view.
Controller:
private IEnumerable<SelectListItem> GetRoles()
{
var dbUserRoles = new DbUserRoles();
var roles = dbUserRoles
.GetRoles()
.Select(x =>
new SelectListItem
{
Value = x.UserRoleId.ToString(),
Text = x.UserRole
});
return new SelectList(roles, "Value", "Text");
}
public ActionResult AddNewUser()
{
var model = new UserRoleViewModel
{
UserRoles = GetRoles()
};
return View(model);
}
References:
SelectListItem
SelectList Constructor (IEnumerable, String, String)
Now that the viewmodel is created the presentation logic is simplified
View:
#model UserRoleViewModel
#Html.LabelFor(m => m.SelectedUserRoleId)
#Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
References:
LabelExtensions.LabelFor
SelectExtensions.DropDownListFor
This will produce:
<label for="SelectedUserRoleId">User Role</label>
<select id="SelectedUserRoleId" name="SelectedUserRoleId">
<option value="1">First Role</option>
<option value="2">Second Role</option>
<option value="3">Etc...</option>
</select>
#Html.DropDownList("ddl",Model.Select(item => new SelectListItem
{
Value = item.RecordID.ToString(),
Text = item.Name.ToString(),
Selected = "select" == item.RecordID.ToString()
}))
One way might be;
<select name="listbox" id="listbox">
#foreach (var item in Model)
{
<option value="#item.UserRoleId">
#item.UserRole
</option>
}
</select>
Something close to:
#Html.DropDownListFor(m => m.UserRole,
new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId),
new { /* any html attributes here */ })
You need a SelectList to populate the DropDownListFor. For any HTML attributes you need, you can add:
new { #class = "DropDown", #id = "dropdownUserRole" }
Instead of a List<UserRole>, you can let your Model contain a SelectList<UserRole>. Also add a property SelectedUserRoleId to store... well... the selected UserRole's Id value.
Fill up the SelectList, then in your View use:
#Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole)
and you should be fine.
See also http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx.
Your call to DropDownListFor needs a few more parameters to flesh it out. You need a SelectList as in the following SO question:
MVC3 DropDownListFor - a simple example?
With what you have there, you've only told it where to store the data, not where to load the list from.
#{
List<CategoryModel> CategoryList = CategoryModel.GetCategoryList(UserID);
IEnumerable<SelectListItem> CategorySelectList = CategoryList.Select(x => new SelectListItem() { Text = x.CategoryName.Trim(), Value = x.CategoryID.Trim() });
}
<tr>
<td>
<B>Assigned Category:</B>
</td>
<td>
#Html.DropDownList("CategoryList", CategorySelectList, "Select a Category (Optional)")
</td>
</tr>
I'm going to approach this as if you have a Users model:
Users.cs
public class Users
{
[Key]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual DbUserRoles DbUserRoles { get; set; }
}
and a DbUserRoles model that represented a table by that name in the database:
DbUserRoles.cs
public partial class DbUserRoles
{
[Key]
public int UserRoleId { get; set; }
[Required]
[StringLength(30)]
public string UserRole { get; set; }
}
Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:
var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;
and have these supporting functions:
private static SelectListItem[] _UserRolesList;
/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
if (_UserRolesList == null)
{
var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
{
Text = a.UserRole,
Value = a.UserRoleId.ToString()
}).ToList();
userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });
_UserRolesList = userRoles.ToArray();
}
// Have to create new instances via projection
// to avoid ModelBinding updates to affect this
// globally
return _UserRolesList
.Select(d => new SelectListItem()
{
Value = d.Value,
Text = d.Text
})
.ToArray();
}
Repository.cs
My Repository function GetAllUserRoles() for the function, above:
public class Repository
{
Model1 db = new Model1(); // Entity Framework context
// User Roles
public IList<DbUserRoles> GetAllUserRoles()
{
return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
}
}
AddNewUser.cshtml
Then do this in your View:
<table>
<tr>
<td>
#Html.EditorFor(model => model.UserName,
htmlAttributes: new { #class = "form-control" }
)
</td>
<td>
#Html.DropDownListFor(model => model.RoleId,
new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
htmlAttributes: new { #class = "form-control" }
)
</td>
</tr>
</table>
#model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
#{
ViewBag.Title = "Detalle";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ingresar Usuario</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
{
new SelectListItem{ Text= "SC", Value = "SC" },
new SelectListItem{ Text= "VC", Value = "VC" },
new SelectListItem{ Text= "IN", Value = "IN" },
new SelectListItem{ Text= "EM", Value = "EM" },
new SelectListItem{ Text= "SP", Value = "SP" },
}, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
{
new SelectListItem{ Text= "Masculino", Value = "M" },
new SelectListItem{ Text= "Femenino", Value = "F" }
}, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
{
new SelectListItem{ Text= "Soltero", Value = "S" },
new SelectListItem{ Text= "Casado", Value = "M" }
}, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
#ViewBag.Message
</div>
<div class="col-md-offset-2 col-md-10" style="color:red">
#ViewBag.ErrorMessage
</div>
</div>
</div>
}