Getting a model error when using MVC4 Compare attribute against a nested property.
Error is as follows Could not find a property named PASSWORD.
What is the correct way to use Compare for Nested Property comparison?
User.cs
public partial class User
{
public User()
{
this.Mobilizations = new HashSet<Mobilization>();
}
[Required(ErrorMessage="Password is required")]
[DataType(DataType.Password)]
public string PASSWORD { get; set; }
}
UserViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using CompareAttribute = System.Web.Mvc.CompareAttribute;
public class userViewModel
{
public User User { get; set; }
[DataType(DataType.Password)]
[Required(ErrorMessage = "CONFIRM PASSWORD is required")]
[Display(Name="CONFIRM PASSWORD")]
[CompareAttribute("PASSWORD",ErrorMessage="Password didnot match")]
public string ComparePassword { get; set; }
public IEnumerable<Designation> DesignationList { get; set; }
public SelectList MenuList { get; set; }
[Required(ErrorMessage="Select some menu items")]
public string[] MenuIds { get; set; }
}
Controller
[HttpPost]
public ActionResult Create(userViewModel model)
{
if (ModelState.IsValid) //<= **Getting Model error here**
{
_db.Entry(model.User).State = EntityState.Modified;
_db.SaveChanges();
}
return RedirectToAction("Create");
}
The View is as follows
<div class="form-group">
#Html.LabelFor(model => model.User.PASSWORD, new { #class = "col-sm-2 control-label " })
<div class="col-sm-6 ">
#Html.EditorFor(model => model.User.PASSWORD, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.User.PASSWORD)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComparePassword, new { #class = "col-sm-2 control-label " })
<div class="col-sm-6 ">
#Html.EditorFor(model => model.ComparePassword, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComparePassword)
</div>
</div>
How can i solve this issue?
Try like this:
[CompareAttribute("User.Password", ErrorMessage="Password didnot match")]
public string ComparePassword { get; set; }
Or, remove the User property from your ViewModel and add
public string Password {get; set;}
[CompareAttribute("Password", ErrorMessage="Password didnot match")]
public string CinfirmPassword {get; set;}
Later you can populate your User object.
And here you can find a workaround.
Related
Using ASP.Net Core, I am developing a simple form to reset the password using email address.
My model is as follow:
public class EmailViewModel
{
[Required(ErrorMessageResourceName = "Model_RequireEmail", ErrorMessageResourceType = typeof(Resources.Identity))]
[Display(Name = "Models_Account_Email", ResourceType = typeof(Resources.Identity))]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Models.EmailFormat")]
[MaxLength(100, ErrorMessage = "Models.MaxLength")]
public string? Email { get; set; }
}
And my view:
<form method="post">
<div class="uk-text-danger">
#Html.ValidationSummary()
</div>
<div class="uk-margin">
<div class="uk-inline">
<span class="uk-form-icon" uk-icon="icon: mail"></span>
#Html.TextBoxFor(m => m.Data.EmailViewModel.Email, new
{
#class = "validate uk-input",
placeholder = Html.DisplayNameFor(m => m.Data.EmailViewModel.Email)
})
#Html.HiddenFor(m => m.Data.ResetPasswordAction)
#Html.HiddenFor(m => m.Data.ResetPasswordController)
</div>
</div>
<button class="uk-button uk-button-default">#Html.LocalizedIdentity("Views.Account.PassReset")</button>
</form>
My issue is that even if I provide a correct email address, I keep getting the message of the "required" data annotation. What did I miss?
EDIT 13/12/2021
The issue occurs when I used a nested ViewModel. For example, the viewModel associated with my form is
public class ForgotPasswordViewModel
{
public EmailViewModel EmailViewModel => new EmailViewModel();
[HiddenInput]
public string? ResetPasswordAction { get; set; }
[HiddenInput]
public string? ResetPasswordController { get; set; }
}
using the EmailViewModel above. This give a ModelState.IsValid= false because the email is null even if provided.
If I bypass the EmailViewModel and use for my ForgotPasswordViewMode, the following:
public class ForgotPasswordViewModel
{
[Display(Name = "Models_Account_Email", ResourceType = typeof(Resources.Identity))]
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Models.EmailFormat")]
[MaxLength(100, ErrorMessage = "Models.MaxLength")]
public string? Email { get; set; }
[HiddenInput]
public string? ResetPasswordAction { get; set; }
[HiddenInput]
public string? ResetPasswordController { get; set; }
}
It works nicely.
The problem is that I want to use the nested ViewModel to avoid repeating it.
Why doesn't it work with the nested EmailViewModel?
This is my model and my test view, it will lead to ModelState.IsValid == false because the input form should have a property of emailVM.Email but not EmailViewModel.
public class EmailViewModel
{
//[Required(ErrorMessageResourceName = "Model_RequireEmail", ErrorMessageResourceType = typeof(Resources.Identity))]
//[Display(Name = "Models_Account_Email", ResourceType = typeof(Resources.Identity))]
[Display(Name = "Models_Account_Email")]
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Models.EmailFormat")]
[MaxLength(100, ErrorMessage = "Models.MaxLength")]
public string? Email { get; set; }
}
public class ForgotPasswordViewModel
{
//public EmailViewModel emailVM => new EmailViewModel();
public EmailViewModel emailVM { get; set; }
[HiddenInput]
public string? ResetPasswordAction { get; set; }
[HiddenInput]
public string? ResetPasswordController { get; set; }
}
<form method="POST" asp-action="Edit">
<div class="uk-text-danger">
#Html.ValidationSummary()
</div>
<div class="uk-inline">
<span class="uk-form-icon" uk-icon="icon: mail"></span>
#Html.TextBoxFor(m => m.emailVM.Email, new
{
placeholder = Html.DisplayNameFor(m => m.emailVM.Email)
})
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
I have a problem with my code. Iwan to make a dropdownlist in my View.cshtml using ViewData and #Html.Dropdownlist. But i get error while i compile it.
Here is my code :
This is the model
public class DeviceComponentModel
{
public int devcomId { get; set; }
public int devcomcomponentId { get; set; }
public int? devcomdeviceId { get; set; }
public ComponentModel Component { get; set; }
public DeviceModel Device { get; set; }
}
This is the code in the controller.
public ActionResult addDevicecomponent()
{
ViewData["Device"] = new SelectList(debuDB.Devices, "Id", "Name");
ViewData["Component"] = new SelectList(debuDB.Components, "Id", "Name");
DeviceComponentModel mdlDevicecom = new DeviceComponentModel();
return View(mdlDevicecom);
}
[HttpPost]
public ActionResult addDeviceComponent(DeviceComponentModel mdlDevicecom)
{
try
{
DeviceComponent deviceComponent = new DeviceComponent()
{
Id = mdlDevicecom.devcomId,
device_id = mdlDevicecom.devcomdeviceId,
component_id = mdlDevicecom.devcomcomponentId
};
debuDB.DeviceComponents.InsertOnSubmit(deviceComponent);
debuDB.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View(mdlDevicecom);
}
}
This is my code in the View
<div class="editor-label">
#Html.LabelFor(model => model.devcomdeviceId)
</div>
<div class="editor-field">
#Html.DropDownList("device_0",ViewData["Device"] as IEnumerable<SelectListItem>, "Choose Device")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.devcomcomponentId)
</div>
<div class="editor-field">
#Html.DropDownList("component_0",ViewData["Component"] as IEnumerable<SelectListItem>, "Choose Component")
</div>
But when i compiled it i got the error like this:
"There is no ViewData item of type 'IEnumerable' that has the key 'device_0'."
I dont know why cant i get the error like that. I hope some of you can give the solution of this error.
Regards,
So I have this problem when trying to save an item to the database in my asp.net mvc4 web app.
I have three classes listed below
public class Posts
{
[Key]
public int PostID { get; set; }
[Required(ErrorMessage="A Title is required for your Post")]
[Display(Name="Title")]
public string PostTitle { get; set; }
[Required(ErrorMessage="This Field is Required")]
[Display(Name = "Post")]
public string PostContent { get; set; }
[Required()]
[DataType(DataType.DateTime)]
public DateTime PostDate { get; set; }
//public int AuthorID { get; set; }
//public int CommentID { get; set; }
[NotMapped]
public virtual List<Comments> Comment { get; set; }
public virtual Users user { get; set; }
}
and this class has a many to one relationship with the users class below
public class Users
{
public Users()
{
}
[Key]
public int UserID { get; set; }
[Required()]
public string Firstname { get; set; }
[Required()]
public string Lastname { get; set; }
[Required()]
[DataType(DataType.Date, ErrorMessage="Enter a Valid Date")]
public DateTime DOB { get; set; }
//[Required()]
//public string Photo { get; set; }
[Required()]
public string Sex { get; set; }
[Required()]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public DateTime RegDate { get; set; }
[Required()]
[Column("Username")]
//[Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name has already been taken. Please enter a different User name.")]
public string Username { get; set; }
[Required()]
[DataType(DataType.Password)]
public string Password { get; set; }
public string PasswordSalt { get; set; }
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage="Passwords do not match")]
[DataType(DataType.Password)]
//[NotMapped]
//public string ConfirmPassword { get; set; }
public virtual List<Posts> Post { get; set; }
public virtual List<Comments> Comment { get; set; }
}
The database table for the Posts.cs class has a field called user_UserID which i assume is to store the id of the user that creates a post. I'm trying to save the posts to the database using the below code
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Posts</legend>
<div class="form-group">
#Html.LabelFor(model => model.PostTitle)
#Html.TextBoxFor(model => model.PostTitle, new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.PostTitle)
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostContent)
#Html.TextAreaFor(model => model.PostContent, new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.PostContent)
</div>
<input type="hidden" name="user.UserID" value="#Session["LoggedUserID"]" />
<div>
<input type="submit" value="Submit" />
</div>
</fieldset>
}
As you can see, the user ID i'm saving to the database table is gotten from the user ID stored in the Session["LoggedUserID"] variable. The controller that handles the saving is below
public class PostsController : Controller
{
//
// GET: /Posts/
BlogContext db = new BlogContext();
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Posts Post)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
try
{
if (ModelState.IsValid)
{
var newPost = db.Post.Create();
newPost.PostTitle = Post.PostTitle;
newPost.PostContent = Post.PostContent;
newPost.PostDate = DateTime.Now;
newPost.user.UserID = Post.user.UserID;
db.Post.Add(newPost);
db.SaveChanges();
return RedirectToAction("Index", "Posts");
}
else
{
ModelState.AddModelError("", "Something is wrong with the model");
}
}
catch (NullReferenceException ex)
{
Debug.WriteLine("Processor Usage" + ex.Message);
}
return View();
}
}
I attached a breakpoint to the Modelstate.IsValid line and then debugged, but i noticed the ModelState is always evaluating to false and the ModelState.AddModelError is showing that is there is something wrong with validating the model. Ive tried all possible tweakings all to no avail. I need help. How can i save the Posts to the database table without this problem.
Please what am i doing wrong?
I suspect ModelState is invalid because you are posting a value for user.UserId (the hidden input) which is initializing the property User which is invalid because of the validation attributes applied to other properties of User. It would be better to create a view model for creating new Posts that contain only the properties you need to display/edit. It is not necessary to include a property for User (the author of the post) since this can be set in the controller when you save the data (similar to what you are doing for the PostDate property
View model
public class PostVM
{
[Required(ErrorMessage="A Title is required for your Post")]
[Display(Name="Title")]
public string Title { get; set; }
[Required(ErrorMessage="This Field is Required")]
[Display(Name = "Post")]
public string Content { get; set; }
}
Controller
[HttpGet]
public ActionResult Create()
{
PostVM model = new PostVM();
return View(model);
}
[HttpPost]
public ActionResult Create(PostVM model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// Initialize new Posts
// Map properties from the view model, set the user and date
// Save and redirect
}
View
#model PostVM
#using (Html.BeginForm()) {
....
<div class="form-group">
#Html.LabelFor(model => model.Title)
#Html.TextBoxFor(model => model.Title, new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Content)
#Html.TextAreaFor(model => model.Content, new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.Content)
</div>
<input type="submit" value="Submit" />
}
I have these two ViewModels
public class AboutViewModel : ViewModel
{
public override long Id { get; set; }
public override string PageTitle { get; set; }
public override string TitleDescription { get; set; }
public override string ContentTitle { get; set; }
public virtual AboutItemViewModel AboutItem { get; set; }
}
public class AboutItemViewModel
{
public long Id { get; set; }
[AllowHtml]
public string Content { get; set; }
public string ImageUrl { get; set; }
public HttpPostedFileBase FileToUpload { get; set; }
}
Here is my controller:
[ValidateInput(false)]
[ValidateAntiForgeryToken, HttpPost]
public ActionResult Create(long? siteid, long? cid, AboutViewModel model)
{
return View(model);
}
Here is my View:
#using (Html.BeginForm("Create", "About", new { siteid = ViewData["siteid"], cid = ViewData["cid"] },FormMethod.Post,new { enctype = "multipart/form-data", #class = "form-horizontal rtl", autocomplete = "off" }))
{
<div class="controls">
<input type="file" name="FileToUpload" id="FileToUpload" style="margin-right: -9px;">
</div>
<div class="controls">
#Html.ValidationMessageFor(o => o.AboutItem.FileToUpload, "", new { id = "spanfile", #class = "alert alert-block alert-error span3 pull-right", style = "margin-right: 160px;" })
</div>
<div class="control-group pull-left">
<button type="submit" class="btn btn-large" data-toggle="button">Save</button>
</div>
}
How to bind the file to FileToUpload to stop returning me a null?
Except:
If I put it in the main AboutViewModel than it's returns a correct value.
Since the FileToUpload property is in the AboutItem proprety, which is a class property of the parent ViewModel, you need to preface the name of your input element with the property it came from. That's a long way of saying that the name of your file input should be AboutItem.FileToUpload.
<input type="file" name="AboutItem.FileToUpload" id="AboutItem_FileToUpload" />
This should take care of the model binding for you. Additionally, you can test this by using an HTML helper on on of the other properties of the AboutItem class. For instance:
#Html.TextBoxFor(x=>x.AboutItem.Id)
This should render in the HTML
<input type="text" name="AboutItem.Id" id="AboutItem_Id />
EDIT
Apparently the id attribute will be rendered with an underscore instead of a dot. However, since the ID attribute is not used in model binding, it shouldn't really matter.
I'm trying to make a simple news system in MVC4. I'm very new at it, and I have a simple News base class that looks like this:
NewsPost:
public class NewsPost
{
public virtual int Id { get; set; }
public virtual string Subject { get; set; }
public virtual string Content { get; set; }
}
It's then attached to a category class like so:
NewsCategory:
public class NewsCategory
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<NewsPost> NewsPosts { get; set; }
}
I then have a controller for creating these NewsPosts:
NewsController:
private readonly INewMvcSiteDataSource _db;
public NewsController(INewMvcSiteDataSource db)
{
_db = db;
}
[HttpGet]
public ActionResult Create()
{
var model = new CreateNewsViewModel();
model.Categories = new SelectList(_db.NewsCategories, "Id", "Name");
return View(model);
}
[HttpPost]
public ActionResult Create(CreateNewsViewModel newsModel)
{
if (ModelState.IsValid)
{
int id = int.Parse(newsModel.SelectedCategories.Single(f => f.Selected).Value);
}
return View(newsModel);
}
And lastly, to facilitate with creating the NewsPost, I use a CreateNewsViewModel, like so:
CreateNewsViewModel:
public class CreateNewsViewModel
{
[Required]
public string Subject { get; set; }
[Required]
public string Content { get; set; }
public SelectList Categories { get; set; }
public SelectList SelectedCategories { get; set; }
}
My view looks like this:
Create.cshtml:
#model NewMvcSite.Models.CreateNewsViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>CreateNewsViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Subject)
#Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Content)
#Html.ValidationMessageFor(model => model.Content)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Categories)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Categories, Model.SelectedCategories)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
For some reason, my viewmodel isn't returned when I click the submit button to create the newspost, and since there is no parameterless constructor for [HttpPost] Create action, it fails with "No parameterless constructor defined for this object."
I've been trying going through other posts here stating the same problem, but I fail to see the connection between what they are doing and what I am doing. I hope there is someone out there who can help me.
Thank you.
If you want to select category from drop down list, first of all you should add property to your model to hold Id of selected category. Something like this (property Category):
public class CreateNewsViewModel
{
[Required]
public string Subject { get; set; }
[Required]
public string Content { get; set; }
public SelectList Categories { get; set; }
public SelectList SelectedCategories { get; set; }
public int Category { get; set; }
}
after that, you should change code to filling model.Category to this:
model.Categories = new SelectList(categories, "Id", "Name", model.Category);
and than, in your view, editor for Category should look like this:
<div class="editor-field">
#Html.DropDownListFor(m => m.Category, Model.Categories);
</div>
model.Categories = new SelectList(_db.NewsCategories, "Id", "Name");
At this line you fill Categories property
#Html.DropDownListFor(model => model.Categories, Model.SelectedCategories)
Here you trying create select with Categories name and SelectedCategories items
int id = int.Parse(newsModel.SelectedCategories.Single(f => f.Selected).Value);
Here you trying get selected item, BUT on form submit you only sending one number, not list. One of your SelectList must be int
I found the solution.
I had to change the ViewModel to this:
public IEnumerable<SelectListItem> Categories { get; set; }
public int SelectedCategoryId { get; set; }
I changed the controller to:
var model = new CreateNewsViewModel
{
Categories = new SelectList(_db.NewsCategories, "Id", "Name")
};
And changed View to this:
#Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories)