Related
I am quite new to asp.net mvc5, and in my app I want to retrieve user info in their profile.
In profile action I'm trying to display the user info and allow them to edit their info too.
But when I run the program I am getting the edit and display view empty.
I am expecting to see the user previous info when they're trying to edit for example.
here is a picture of what I want:
this is my action :
[HttpGet]
public ActionResult DriverProfile()
{
var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
var authManager = HttpContext.GetOwinContext().Authentication;
ProfileModel driver = new ProfileModel();
IdentityUser theUser = new IdentityUser() { UserName = driver.email, Email = driver.email };
driver = new ProfileModel(theUser);
return View("DriverProfile", driver);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DriverProfile(ProfileModel profile)
{
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new RidesDbContext()));
IdentityUser theUser = new IdentityUser() { UserName = profile.email, Email = profile.email };
IdentityResult theResult = manager.Create(theUser, profile.PasswordHash);
var currentUser = manager.FindById(User.Identity.GetUserId());
currentUser.UserName = profile.email;
currentUser.Email = currentUser.Email;
return Redirect("DriverProfile");
}
I have the profile model as the following:
public class ProfileModel
{
public ProfileModel()
{
}
public ProfileModel(IdentityUser theUser)
{
}
[Display(Name = "Id")]
public int driverId { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "Pleas Enter Your First Name")]
public string firstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Pleas Enter Your Last Name")]
public string lastName { get; set; }
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
[Required(ErrorMessage = "Pleas Enter Your Email Address")]
[RegularExpression(".+\\#.+\\..+", ErrorMessage = "Please Enater a Valid Email Address")]
public string email { get; set; }
[Display(Name = "Mobile Number")]
[Required(ErrorMessage = "Pleas Enter Your Mobile Number")]
public string phoneNumber { get; set; }
[Display(Name = "Address")]
[Required(ErrorMessage = "Pleas Enter Your Address")]
public string Address { get; set; }
[Display(Name = "City")]
[Required(ErrorMessage = "Pleas Enter Your City")]
public string city { get; set; }
[Display(Name = "State")]
[Required(ErrorMessage = "Pleas Enter Your state")]
public string state { get; set; }
[Display(Name = "Car")]
[Required(ErrorMessage = "Please Identify Your Car")]
public string car { get; set; }
[Display(Name = "Driver's License")]
[Required(ErrorMessage = "Please Enter Your Driver's Licende Number")]
public string driverslicense { get; set; }
[Display(Name = "Profile Image")]
[Required]
public byte[] profileImg { get; set; }
public string profileImgType { get; set; }
[Display(Name = "License Image")]
[Required]
public byte[] licenseImg { get; set; }
public string licenseImgType { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Please Enter a password")]
public string PasswordHash { get; set; }
}
How would I get the user info in their profile with an edit option?
I would appreciate your help. Thank you.
Edit:
the view is as the following:
#model RidesApp.Models.ProfileModel
#{
ViewBag.Title = "DriverProfile";
Layout = "~/Views/Shared/DriversViewPage.cshtml";
}
<h2>DriverProfile</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProfileModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.driverId)
<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.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.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.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.city, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.city, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.city, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.state, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.state, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.state, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.car, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.car, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.car, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.driverslicense, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.driverslicense, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.driverslicense, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.profileImgType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.profileImgType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.profileImgType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.licenseImgType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.licenseImgType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.licenseImgType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.PasswordFor(model => model.PasswordHash, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PasswordHash, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Edit Profile" class="btn btn-default" />
</div>
</div>
</div>
}
If I understand the question correctly, You want to edit the IdentityUser Class right?
Given that you already assign values in your controller.
First, we add the IdentityUser class to your ProfileModel Class
public class ProfileModel{
public IdentityUser User{get;set;}
//other profilemodel properties
}
on your view:
<div class="form-group">
#Html.LabelFor(model => model.User.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User.Email, "", new { #class = "text-danger" })
</div>
</div>
or if you just want to show up some values in editing,
you need to assign the value of your ProfileModel
Controller:
ProfileModel driver = new ProfileModel();
//code that assigns values to each property
driver.email = "sample#sample.com";
return View("DriverProfile",driver);
I've seen multiple instances of this question. Be that as it may, I still cannot figure out what the issue is with this post method not passing back the model to the controller. I've looked at naming conventions between the model being passed into the controller, as well as whether or not the read only fields were being passed in if I had removed them. Other than that, it might be the BindAttribute, binding the RoleIds of the multi-select to the model.
Here's my code:
the model:
public class UserDetail
{
public Guid Id { get; set; }
public List<string> RoleIds { get; set; }
public string DomainName { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public string PhysicalDeliveryOfficeName { get; set; }
public string TenantDisplayId { get; set; }
public Boolean InitPassword { get; set; }
public Boolean Active { get; set; }
public Boolean SystemAdmin { get; set; }
public ICollection<RoleDetail> Roles { get; set; }
public IEnumerable<SelectedRoles> SelectedRoles { get; set; }
public MultiSelectList RoleOptions { get; set; }
public UserDetail()
{
Id = Id;
RoleIds = RoleIds;
FirstName = FirstName;
LastName = LastName;
Name = Name;
Active = Active;
EmailAddress = EmailAddress;
SystemAdmin = SystemAdmin;
}
}
cshtml:
#model IzendaEmbedded.Models.UserDetail
#using (Html.BeginForm("EditActiveDirectoryUser","ActiveDirectory",
FormMethod.Post, new {userDetail = Model}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<nav aria-label="breadcrumb">
<ol class="breadcrumb" style="height: 100px; padding-top: 20px; padding-left: 140px; background-color: #FFFFFF">
<li class="breadcrumb-item" style="font-family: arial; font-size:40px"><a href=#Url.Action("Index", "Home")>Izenda</a></li>
<li class="breadcrumb-item active" aria-current="page" style="font-family: arial; font-size:40px"><a href=#Url.Action("Parse", "ActiveDirectory")>Active Directory</a></li>
<li class="breadcrumb-item active" aria-current="page" style="font-family: arial; font-size:40px">Edit Izenda User</li>
</ol>
</nav>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, "Account Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, "First Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, "Last Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailAddress, "Email Address", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.EmailAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Roles, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.ListBoxFor(model => model.RoleIds, Model.RoleOptions, new {#class = "form-control"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
<div class="checkbox">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-4">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
The controller post method:
[HttpPost]
public async Task<ActionResult> EditActiveDirectoryUser([Bind(Include =
"Id, Name, RoleIds")] UserDetail userDetail)
{
//save logic
}
I am working on small ticket system for operations maintenance services comp.
Customer open a ticket and gives general information like location,
category description etc.
After technician fix the problem he must give sum details of the
problem from predefined set, use later for statistical reports.
My problem the repair method unable to post updated values to database plus nothing added to Defects_List table.
Note: I used this tutorial as guide
Models:
public partial class Tickets
{
public Tickets()
{
this.DefectsList = new HashSet<Defects_List>();
}
[Key]
[Display(Name = "Ticket Id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Ticket_Id { get; set; }
[Display(Name = "Project")]
public int Project_Id { get; set; }
[Display(Name = "Issue Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Issue_Date { get; set; }
[Display(Name = "Category")]
[DisplayFormat(NullDisplayText = "[Not set]")]
public int Category_Id { get; set; }
//Other Properties Removed for clarity
public virtual Business_Category businessCategories { get; set; }
public virtual ICollection<Defects_List> DefectsList { get; set; }
}
public partial class Business_Category
{
public Business_Categories()
{
this.Tickets = new HashSet<Tickets>();
this.Malfunctions = new HashSet<Malfunctions>();
}
[Key]
[Display(Name="Category Id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Category_Id { get; set; }
[Display(Name = "Name (eng)")]
[StringLength(60, ErrorMessage = "Name cannot be longer than 60 characters.")]
public string Category_Name { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
public virtual ICollection<Manufacturers> Manufacturers { get; set; }
public virtual ICollection<Malfunctions> Malfunctions { get; set; }
}
public partial class Defects_List
{
[Key, Column(Order = 0)]
[Display(Name = "Ticket Id")]
public int Ticket_Id { get; set; }
[Key, Column(Order = 1)]
[Display(Name = "Malfunction Id")]
public int Malfunction_Id { get; set; }
[StringLength(125, ErrorMessage = "Other cannot be longer than 125 characters.")]
public string Other { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
public virtual Malfunctions Malfunctions { get; set; }
}
Controller:
// GET: /Tickets/Edit/5
public ActionResult Repair(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var tickets = db.nt_Tickets
.Include(t => t.DefectsList).Where(t => t.Ticket_Id == id)
.Single();
if (tickets == null)
{
return HttpNotFound();
}
PopulateSelectedDefects(tickets);
//Other codes Removed for clarity
return View(tickets);
}
private void PopulateSelectedDefects(nt_Tickets Tickets)
{
int categoryId;
if (Tickets.Category_Id == 2)
categoryId = 1;
else categoryId = Tickets.Category_Id;
var allDefects = (from m in db.sys_Malfunctions
where m.Category_Id == categoryId
select m).ToList();
var ticketDefects = new HashSet<int>(Tickets.DefectsList.Select(t => t.Malfunction_Id));
var viewModel = new List<TicketDefectsViewModel>();
foreach (var defect in allDefects)
{
viewModel.Add(new TicketDefectsViewModel
{
Malfunction_Id = defect.Malfunction_Id,
Malfunction_Name_e = defect.Malfunction_Name_e,
IsSelected = ticketDefects.Contains(defect.Malfunction_Id)
});
}
ViewBag.Defects = viewModel;
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Repair(int? id, string[] selectedDefects)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var ticketToUpdate = db.nt_Tickets
.Include(i => i.DefectsList)
.Where(i => i.Ticket_Id == id)
.Single();
if (TryUpdateModel(ticketToUpdate, "",
new string[] { Ticket_Id,Project_Id,Category_Id,Subject,Workshop_Id,Requested_By,Requestor_Mobile, Requestor_eMail,Location_Id,Ticket_Status,Periority_Id,Assigned_To,Description,Issue_Date,Created_By,Created_Date,Updated_By,Updated_Date" }))
{
ticketToUpdate.Updated_By = User.Identity.Name;
ticketToUpdate.Updated_Date = DateTime.UtcNow;
db.Entry(ticketToUpdate).State = EntityState.Modified;
SetTicketDefects(selectedDefects, ticketToUpdate);
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
if (!string.IsNullOrEmpty(message))
ViewBag.errorMessage = message;
}
return View("Error");
}
throw raise;
}
}
PopulateSelectedDefects(ticketToUpdate);
return View("Index");
}
private void SetTicketDefects(string[] selectedDefects, Tickets ticketToUpdate)
{
if (selectedDefects == null)
{
ticketToUpdate.DefectsList = new List<Defects_List>();
return;
}
var selectedDefectsHS = new HashSet<string>(selectedDefects);
var tcketDefects = new HashSet<int>
(ticketToUpdate.DefectsList.Select(c => c.Ticket_Id));
foreach (var defect in db.DefectsLists)
{
if (selectedDefectsHS.Contains(defect.Malfunction_Id.ToString()))
{
if (!tcketDefects.Contains(defect.Malfunction_Id))
{
ticketToUpdate.DefectsList.Add(defect);
}
}
else
{
if (tcketDefects.Contains(defect.Malfunction_Id))
{
ticketToUpdate.DefectsList.Remove(defect);
}
}
}
}
db.DefectsLists here [foreach (var defect in db.DefectsLists)] always empty.
Repair View:
#using (Html.BeginForm("Repair", "Tickets", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
#*#using (Html.BeginForm())*#
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Ticket_Id)
#Html.HiddenFor(model => model.Issue_Date)
#Html.HiddenFor(model => model.Created_By)
#Html.HiddenFor(model => model.Project_Id)
#Html.HiddenFor(model => model.Created_Date)
<div class="form-group">
#Html.Label("Ticket_Id", new { #class = "control-label col-md-2" })
<div class="col-md-1 " style="margin-top:7px">
#Html.DisplayFor(model => model.Ticket_Id)
</div>
#Html.LabelFor(model => model.Issue_Date, new { #class = "control-label col-md-2" })
<div class="col-md-2" style="margin-top:7px">
#Html.DisplayFor(model => model.Issue_Date, new { #class = "form-control" })
</div>
#Html.LabelFor(model => model.Category_Id, new { #class = "control-label col-md-2" })
<div class="col-md-3" style="margin-top:7px">
#Html.DropDownList("Category_Id", null, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Subject, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="margin-top:7px">
#Html.DisplayFor(model => model.Subject, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="margin-top:7px">
#Html.DisplayFor(model => model.Description, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Requested_By, new { #class = "control-label col-md-2" })
<div class="col-md-5" style="margin-top:7px">
#Html.DisplayFor(model => model.Requested_By, new { #class = "form-control" })
</div>
#Html.LabelFor(model => model.Requestor_Mobile, new { #class = "control-label col-md-2" })
<div class="col-md-3" style="margin-top:7px">
#Html.DisplayFor(model => model.Requestor_Mobile, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Requestor_eMail, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="margin-top:7px">
#Html.DisplayFor(model => model.Requestor_eMail, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ticket_Status, new { #class = "control-label col-md-2" })
<div class="col-md-4" style="margin-top:7px">
#Html.EnumDropDownListFor(model => model.Ticket_Status, new { #class = "form-control" })
</div>
#Html.LabelFor(model => model.Periority_Id, new { #class = "control-label col-md-2" })
<div class="col-md-4" style="margin-top:7px">
#Html.EnumDropDownListFor(model => model.Periority_Id, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location_Id, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("Location_Id", null, new { #class = "form-control", #disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Location_Id)
</div>
#Html.LabelFor(model => model.Assigned_To, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("Assigned_To", null, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.Label("Defects")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<table class="table table-hover">
<tr>
#{
int cnt = 0;
List<MaintCare.ViewModels.TicketDefectsViewModel> defects = ViewBag.Defects;
foreach (var defect in defects)
{
if (cnt++ % 3 == 0)
{
#:</tr><tr>
}
#:<td>
<input type="checkbox"
name="selectedDefects"
value="#defect.Malfunction_Id"
#(Html.Raw(defect.IsSelected ? "checked=\"checked\"" : "")) />
#defect.Malfunction_Name_e
#:</td>
}
#:</tr>
}
</table>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-2">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Net I was trying to do a Edit for uploading a image but now whenever I edit it crashes and gives 'System.ArgumentNullException' occurred in System.Core.dll but was not handled in user code'. This all started when I tried to implement an edit for the image upload. It crashes on the edit.cshtml page, I have placed a comment right where it crashes. Any help would be really appreciated, if you require any more information please let me know
AnimalsController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "LatinNameID,CommonNameID,LatinName,CommonName,GenusID,SpeciesID,Description,FamilyID,CountryID,ContinentID,OrderID")] Animal animal, HttpPostedFileBase upload,string latinID,string commonID)
{
var animalToUpdate = db.Animals.Find(latinID,commonID);
//Does a check to see if entry exists in database
if ((db.Animals.Any(ac => ac.LatinName.Equals(animal.LatinName))) || (db.Animals.Any(ac => ac.CommonName.Equals(animal.CommonName))))
{
ModelState.AddModelError("LatinName", "Already Exists");
ModelState.AddModelError("CommonName", "Duplicate Entry");
}
else
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
if (animalToUpdate.Files.Any(f => f.FileType == FileType.Avatar))
{
db.File.Remove(animalToUpdate.Files.First(f => f.FileType == FileType.Avatar));
}
var avatar = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = FileType.Avatar,
ContentType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
avatar.Content = reader.ReadBytes(upload.ContentLength);
}
animalToUpdate.Files = new List<File> { avatar };
}
db.Entry(animal).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.ContinentID = new SelectList(db.Continents, "ContinentID", "ContinentName", animal.ContinentID);
ViewBag.CountryID = new SelectList(db.Countries, "CountryID", "CountryName", animal.CountryID);
ViewBag.FamilyID = new SelectList(db.Families, "FamilyID", "FamilyName", animal.FamilyID);
ViewBag.GenusID = new SelectList(db.Genus, "GenusID", "GenusName", animal.GenusID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderName", animal.OrderID);
ViewBag.SpeciesID = new SelectList(db.Species, "SpeciesID", "SpeciesName", animal.SpeciesID);
return View(animal);
}
Edit View
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Animals", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Animal</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.LatinNameID)
#Html.HiddenFor(model => model.CommonNameID)
<div class="form-group">
#Html.LabelFor(model => model.LatinName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LatinName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LatinName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommonName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CommonName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CommonName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GenusID, "GenusID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenusID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GenusID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SpeciesID, "SpeciesID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SpeciesID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SpeciesID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FamilyID, "FamilyID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FamilyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.FamilyID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountryID, "CountryID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CountryID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContinentID, "ContinentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ContinentID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ContinentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderID, "OrderID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("OrderID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.OrderID, "", new { #class = "text-danger" })
</div>
</div>
//Crashes here
#if (Model.Files.Any(f => f.FileType == FileType.Avatar))
{
<div class="form-group">
<span class="control-label col-md-2"><strong>Current Avatar</strong></span>
<div class="col-md-10">
<img src="~/File?id=#Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" />
</div>
</div>
}
<div class="form-group">
#Html.Label("Avatar", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="Avatar" name="upload" />
</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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Model
//Animal
public class Animal
{
[Key, Column(Order = 0)]
public string LatinNameID { get; set; }
public string LatinName { get; set; }
[Key, Column(Order = 1)]
public string CommonNameID { get; set; }
public string CommonName { get; set; }
public string GenusID { get; set; }
public string SpeciesID { get; set; }
public string Description { get; set; }
public string FamilyID { get; set; }
public string CountryID { get; set; }
public string ContinentID { get; set; }
public string OrderID { get; set; }
public virtual Continent Continent { get; set; }
public virtual Genus Genus { get; set; }
public virtual Species Species { get; set; }
public virtual Family Family { get; set; }
public virtual Country Country { get; set; }
public virtual Order Order { get; set; }
public virtual ICollection<File> Files { get; set; }
}
//File
public class File
{
public int FileId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public FileType FileType { get; set; }
public string LatinNameID { get; set; }
public string CommonNameID { get; set; }
public virtual Animal Animal { get; set; }
}
The error that you are getting suggests that you are calling a method with a null argument somewhere in your code. Since it crashes with the if statement beginning with Model.Files.Any(f => f.FileType == FileType.Avatar), I would verify that Model.Files is not null before proceeding.
The code could look like the following:
#if (Model.Files != null && Model.Files.Any(f => f.FileType == FileType.Avatar))
{
<div class="form-group">
<span class="control-label col-md-2"><strong>Current Avatar</strong></span>
<div class="col-md-10">
<img src="~/File?id=#Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" />
</div>
</div>
}
If Model.Files should never be null, then you might need to investigate why that value is not being set as well.
I'm trying to use Data Annotations in my MVC project (Mono/.NET 4.5). I've created my model and added all the appropriate annotations. I have my view and controller appropriately wired up. However, the validation just doesn't seem to be happening. I've tried everything I can find to no avail. As this is my first time working with Razor and Data Annotations, I imagine there is some setup piece I'm missing but I can't find it for the life of me. Here's my code:
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MyWebsite
{
public class RegisterViewModel : BaseViewModel
{
#region properties
[Required(ErrorMessage = "Required")]
[StringLength(50)]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(100)]
[DisplayName("Last Name")]
public string LastName { get; set; }
[StringLength(50)]
[DisplayName("Display Name")]
public string DisplayName { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(255)]
[DisplayName("Email Address")]
public string EmailAddress { get; set; }
#endregion
#region ctor
public RegisterViewModel ()
{
}
#endregion
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyWebsite.Controllers
{
public class AccountController : Controller
{
public ActionResult Register()
{
ViewData ["IsComplete"] = false;
ViewData ["RequiredVouches"] = WebSettings.RequiredVouches;
return View ();
}
[HttpPost]
public ActionResult Register(FormCollection formData)
{
if (ModelState.IsValid) {
//TODO: Put the data
ViewData ["IsComplete"] = true;
}
return View ();
}
}
}
View
#model SummerIsles.Web.RegisterViewModel
#section Styles {
<link href="~/Content/themes/base/Account.css" rel="stylesheet" type="text/css" />
}
#{
if((bool)#ViewData["IsComplete"]) {
<h1>Registration Request Complete!</h1>
<div class="page-message">
<p>
Confirmation message goes here
</p>
</div>
}
else {
<h1>Registration</h1>
<div class="page-message">
<p>
Instruction text goes here
</p>
</div>
using (Html.BeginForm()) {
#Html.ValidationSummary(false)
<fieldset>
<legend>Your Information</legend>
<div class="group column-1">
#Html.LabelFor(modelItem => #Model.FirstName)
#Html.EditorFor(modelItem => #Model.FirstName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.FirstName)
#Html.LabelFor(modelItem => #Model.DisplayName)
#Html.EditorFor(modelItem => #Model.DisplayName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.DisplayName)
</div>
<div class="group column-2">
#Html.LabelFor(modelItem => #Model.LastName)
#Html.EditorFor(modelItem => #Model.LastName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.LastName)
#Html.LabelFor(modelItem => #Model.EmailAddress)
#Html.EditorFor(modelItem => #Model.EmailAddress, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.EmailAddress)
</div>
<div class="button-options">
<button id="btnSubmit" type="submit" formmethod="post" class="btn btn-danger">Submit</button>
<a id="btnCancel" href="~/" class="btn">Cancel</a>
</div>
</fieldset>
}
}
}
Also, I have added the jquery validation scripts to my layout file and have also enabled client validation in the web.confg.
Layout Header
<head>
<!--some other css and such-->
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobstrusive.min.js"></script>
</head>
Web.config
<appSettings>
<!--some other stuff-->
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Basically, when I click submit, it thinks the model is perfectly valid (ModelState.IsValid returns true in the controller) and the validation stuff (which I would expect to fire before the post back to the controller) never seems to fire. I get no validation messages even with a completely blank form (despite having the "Required" data annotation). What am I missing?
#Html.ValidationMessageFor(modelItem => #Model.LastName)
should be
#Html.ValidationMessageFor(modelItem => modelItem.LastName)
for all your HtmlHelpers, including TextBoxFor and LabelFor etc.
Also
public ActionResult Register(FormCollection formData)
should be
public ActionResult Register(RegisterViewModel model)
in order for your server side ModelState.IsValid to work.
$(document).ready(function () {
$(".ChkBooks").click(function () {
var chkslst = $(".ChkBooks");
var CheckedList = "";
debugger;
$.each(chkslst, function (index, data) {
if (data.checked) {
CheckedList += data.value + ",";
}
});
$("#BookNames").val(CheckedList);
});
});
[Key]
public int Eno { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Name is required")]
[RegularExpression(#"^[a-zA-Z]+$",ErrorMessage = "Pls Enter Only Charaters")]
[StringLength(100, MinimumLength = 3,ErrorMessage = "Name Length Minimun 3 is required")]
public string Ename { get; set; }
[DisplayName("Employee salary")]
//[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[Required(ErrorMessage = "salary is required")]
[Range(3000, 10000000, ErrorMessage = "Salary must be between 3000 and 10000000")]
public int salary { get; set; }
[DisplayName("Image")]
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase Image { get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "Email is required")]
[RegularExpression(#"^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$", ErrorMessage ="Please Enter Valid EmailID")]
public string Email { get; set; }
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DisplayName("ConfirmPassword")]
[Required(ErrorMessage = "Password is required")]
[Compare("Password", ErrorMessage = "Password is Not Matching")]
public string ConfirmPassword { get; set; }
[DisplayName("PHONENumber")]
[Required(ErrorMessage = "PhoneNmber is required")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[StringLength(10,ErrorMessage ="maxlimit 10")]
public string PhoneNmber { get; set; }
[DisplayName("Age")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[Required(ErrorMessage = "Age is required")]
public int Age { set; get; }
[DisplayName("Gender")]
[Required(ErrorMessage = "Gender is required")]
public bool Gender { get; set; }
[DisplayName("Date")]
[Required(ErrorMessage = "Date is required")]
public DateTime DateandTime { get; set; }
[DisplayName("BookNames")]
[Required(ErrorMessage = "Date is required")]
public List<string> BookNames { get; set; }
}
#{
ViewBag.Title = "Registration";
List<Books> BooksLists = (List<Books>)ViewBag.BooksList;
}
<h2>Registration</h2>
#*#using (Html.BeginForm())*#
#using (Html.BeginForm("Registration", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employees</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Ename, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ename, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ename, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.salary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.salary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.salary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Image, new { #type = "file", #accept = "image/x-png,image/gif,image/jpeg" }) #*image/**#
#Html.ValidationMessageFor(model => model.Image, "", 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.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.ConfirmPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PhoneNmber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.PhoneNmber, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.TextBoxFor(model => model.PhoneNmber, "{0:c}", new { #class = "required numeric", id = "CurrentBalance" })
#Html.ValidationMessageFor(model => model.PhoneNmber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#*#Html.RadioButtonFor(m => m.Gender, "true") <label> Male </label>
#Html.RadioButtonFor(m => m.Gender, "false") <label> Female </label>*#
#Html.DropDownListFor(model => model.Gender, new SelectList(new List<Object>{
new { value = "" , text = "Select" },
new { value = 1 , text = "Male" },
new { value = 0 , text = "Female"} }, "value", "text", 0))
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateandTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateandTime, new { htmlAttributes = new { #class = "form-control", #type = "date" } })
#Html.ValidationMessageFor(model => model.DateandTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookNames, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (Model != null)
{
for (int i = 0; i < #BooksLists.Count; i++)
{
#Html.CheckBox(Convert.ToString(#BooksLists[i].BookName), false, new { #class = "ChkBooks", style = "margin-left: 20px;vertical-align: 1px;width: 16px;height: 16px; ", #type = "checkbox", #value = Convert.ToString(#BooksLists[i].BookId) })
#BooksLists[i].BookName;
}
}
else
{
for (int i = 0; i < #BooksLists.Count(); i++)
{
#Html.CheckBox(Convert.ToString(BooksLists[i].BookName), false, new { #class = "ChkBooks", style = "margin-left: 20px;vertical-align: 1px;width: 16px;height: 16px; ", #type = "checkbox", #value = Convert.ToString(#BooksLists[i].BookId) })
#BooksLists[i].BookName;
}
}
<br />
#Html.TextBoxFor(m => m.BookNames, new { #class = "form-control", style = "display: none",#readonly = true })
#Html.ValidationMessageFor(model => model.BookNames, "", 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>