Following is my code and I don't know why my validator is not working
First code is User model then second is home controller and last is view of the Index action result.I am new to MVC.COuld you please help me.
Thanks
public class User
{
[Required(ErrorMessage = "UserName is required")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Pasword { get; set; }
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string uname,string pass)
{
if(ModelState.IsValid)
{
User user = new User();
user.UserName = uname;
user.Pasword = pass;
string Username = ConfigurationManager.AppSettings["username"].ToString();
string passwrd = ConfigurationManager.AppSettings["password"].ToString();
if (user.UserName !=null && user.Pasword !=null)
{
if(user.UserName==Username && user.Pasword==passwrd)
{
return RedirectToAction("Detail", "Home");
}
}
}
return View("Index");
}
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<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.Pasword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pasword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pasword, "", new { #class = "text-danger" })
</div>
</div>
first of all you should send model instead of individual properties like
[HttpPost]
public ActionResult Index(User user)
{
if(!ModelState.IsValid)
{
return View("Index",user);
}
// your code here if model is valid
return View("Index");
}
it will check if ModelState is Invalid it will redirect to the same view with ModelState which will include key and value so if validation of a property fails its name will be the key and message will be in the value of the key validation messages will be populated according to their keys(property names)
Related
when i tried to submit my edit form i get this issue and i don't know why
productsController edit get
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//ProductsModel productsModel = await db.ProductsModels.FindAsync(id);
var products = await db.ProductsModels.Include(a =>a.categorieId).Include(a => a.users).FirstAsync(a => a.id == id);
if (products == null)
{
return HttpNotFound();
}
var selectedOwnerId = products.users?.Id ?? string.Empty;
var users = db.Users.Select(userItem => new SelectListItem
{
Text = userItem.Email,
Value = userItem.Id,
Selected = userItem.Id == selectedOwnerId
}).ToSafeReadOnlyCollection();
var selectedCategoryId = products.categorieId.id;
var productCategories = db.ProductCategoriesModels
.Select(a => new SelectListItem
{
Value = a.id.ToString(),
Text = a.name,
Selected = a.id == selectedCategoryId
}).ToSafeReadOnlyCollection();
var viewmodel = new productCreatEditViewModel()
{
Products = products,
productCategories = productCategories,
users = users
};
//ViewBag.users = userList;
//ViewBag.productcategorieId = new SelectList(db.ProductCategoriesModels, "id", "Name", productsModel.productcategorieId);
return View(viewmodel);
}
productsController edit post
// POST: Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "id,name,calorie,price,productcategorieId,userId")] ProductsModel productsModel)
{
if (ModelState.IsValid)
{
db.Entry(productsModel).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.productcategorieId = new SelectList(db.ProductCategoriesModels, "id", "Name", productsModel.productcategorieId);
return View(productsModel);
}
edit view
#model koelkast.ViewModels.productCreatEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProductsModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Products.id)
<div class="form-group">
#Html.LabelFor(model => model.Products.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.calorie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.calorie, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.calorie, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.categorieId.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => Model.Products.categorieId.id,Model.productCategories, new { Name = "productCategoriesId", #class ="form-control"})
#Html.ValidationMessageFor(model => model.productCategories, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.users.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => Model.Products.users.Id,Model.users, new {Name = "UserId", #class = "form-control" })
#Html.ValidationMessageFor(model => model.Products.users.Email, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
ViewModel
The model item passed into the dictionary is of type 'koelkast.Models.ProductsModel', but this dictionary requires a model item of type 'koelkast.ViewModels.productCreatEditViewModel'.
namespace koelkast.ViewModels
{
public class productCreatEditViewModel
{
[Required]
public ProductsModel Products { get; set; }
[Required]
public ICollection<SelectListItem> productCategories { get; set; }
[Required]
public ICollection<SelectListItem> users { get; set; }
}
}
productModel
namespace koelkast.Models
{
public class ProductsModel
{
[Key]
public int id { get; set; }
[Required,Display(Name = "name")]
public string name { get; set; }
//display name is de naam die hij gaat laten zien als nnaam in je view
[Required, Display(Name = "calorie")]
public int calorie { get; set; }
[Required, Display(Name = "price")]
public float price { get; set; }
[Display(Name = "categories")]
//hier zet je die foreing key
//zoals je kunt zien roep ik alleen de model aan
public int? productcategorieId { get; set; }
[ForeignKey("productcategorieId")]
public virtual ProductCategoriesModel categorieId { get; set; }
//je zegt hier dus dat dit de Id is(userId)
//van applicationUser table users
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser users { get; set; }
}
}
https://i.stack.imgur.com/Qaq67.png
you have a bug here, fix it
public async Task<ActionResult> Edit(ProductsModel productsModel)
{
}
you have 2 choices
1.Change ProductsModel to ProductCreatEditViewModel
or
Return ProductCreatEditViewModel as model
var viewmodel = new productCreatEditViewModel()
{
Products = productsModel,
productCategories = productCategories,
users = users
};
return View(viewModel);
I am fairly new to coding, and am working on a personal MVC project. I am trying to implement a DropDown that uses values submitted by the user. I believe I have almost everything written correctly, but when I go to update an entity, I get the following error:
The ViewData item that has the key 'WrestlerId' is of type 'System.Int32' but must be of type 'IEnumerable'.
Any assistance with this would be appreciated, and I will edit/update to help figure this out.
Edit: The error itself happens in the View on the following line of code:
#Html.DropDownListFor(x => Model.WrestlerId, Model.Wrestlers, htmlAttributes: new { #class = "form-control" })
Model
public class TitleEdit
{
public int TitleId { get; set; }
public string TitleName { get; set; }
[Display (Name = "Favorite")]
public bool IsStarred { get; set; }
[Display(Name ="Date Established")]
public DateTime DateEstablished { get; set; }
[Display(Name = "Current Champion")]
public int? WrestlerId { get; set; }
public string WrestlerName { get; set; }
public IEnumerable<SelectListItem> Wrestlers { get; set; }
}
View
#model Models.TitleCRUD.TitleEdit
#{
ViewBag.Title = "Edit";
}
<h2>Updating Title</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.TitleId)
<div class="form-group">
#Html.LabelFor(model => model.TitleName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TitleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TitleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsStarred, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsStarred)
#Html.ValidationMessageFor(model => model.IsStarred, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateEstablished, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateEstablished, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateEstablished, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WrestlerId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => Model.WrestlerId, Model.Wrestlers, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Wrestlers, "", 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 id="linkColor">
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller
//GET: Edit
public ActionResult Edit(int id)
{
var service = CreateTitleService();
var detail = service.GetTitleById(id);
var wrestlerList = new WrestlerRepo();
var model = new TitleEdit
{
TitleId = detail.TitleId,
TitleName = detail.TitleName,
IsStarred = detail.IsStarred,
DateEstablished = detail.DateEstablished,
WrestlerId = detail.WrestlerId
};
model.Wrestlers = wrestlerList.GetWrestlers();
return View(model);
}
//POST: Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, TitleEdit model)
{
if (!ModelState.IsValid)
{
var wrestlerList = new WrestlerRepo();
model.Wrestlers = wrestlerList.GetWrestlers();
return View(model);
}
if (model.TitleId != id)
{
ModelState.AddModelError("", "ID Mismatch");
return View(model);
}
var service = CreateTitleService();
if (service.UpdateTitle(model))
{
TempData["SaveResult"] = "The title has been updated!";
return RedirectToAction("Index");
}
ModelState.AddModelError("", "The title could not be updated.");
return View(model);
}
GetWrestlers()
public IEnumerable<SelectListItem> GetWrestlers()
{
using (var ctx = new ApplicationDbContext())
{
List<SelectListItem> wrestlers = ctx.Wrestlers.AsNoTracking()
.OrderBy(n => n.RingName)
.Select(n =>
new SelectListItem
{
Value = n.WrestlerId.ToString(),
Text = n.RingName
}).ToList();
var wrestlerTip = new SelectListItem()
{
Value = null,
Text = "Select a Wrestler"
};
wrestlers.Insert(0, wrestlerTip);
return new SelectList(wrestlers, "Value", "Text");
}
}
There are two tables Roles and Administrator. I have a foreign key in the administrator table which references to the RoleId. So, I performed linq query to get all the roles and admin data from the SQL server. Then in the MVC App of the asp.net, I created two model classes as shown below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
namespace FastFactsTestPortalMVCApp.Models
{
public class Administrator
{
public int AdminId { get; set; }
public string AdminFirstName { get; set; }
public string AdminLastName { get; set; }
public string AdminEmail { get; set; }
public string AdminUserName { get; set; }
public string AdminPassword { get; set; }
public string AdminContactNumber { get; set; }
public string AdminDesignation { get; set; }
public int AdminRoleId { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public Nullable<System.DateTime> UpdatedAt { get; set; }
[ForeignKey("RoleId")]
public virtual Role Role { get; set; }
}
}
Model Role Class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FastFactsTestPortalMVCApp.Models
{
public class Role
{
public Role()
{
this.Administrators = new HashSet<Administrator>();
this.HRs = new HashSet<HR>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public Nullable<System.DateTime> UpdatedAt { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Administrator> Administrators { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<HR> HRs { get; set; }
}
}
Then using admin controller, I wanted to register a user. In that case I wanted to create a view, where i retrieve data of roles from linq query and display the role name, so that the user can register with the role name.
For that I used Create Function which is given below in the admin controller:
[AllowAnonymous]
public ActionResult RegisterAdmin()
{
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
ViewBag.RoleId = repObj.GetRoles();
return View();
}
Then I coded a function to save the input values from the user :
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveRegisteredAdmin(Models.Administrator userObj)
{
if(ModelState.IsValid)
{
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
var returnValue = repObj.AddAdmin(userObj);
if(returnValue)
{
return RedirectToAction("Login", "Home");
}
else
{
return View("Error");
}
}
return View("RegisterAdmin");
}
For the Register Admin, I created a View also, where the error exists. The error in the view says Null after registering the or clicking on the submit button. The null error was referred to DropDownList.
The Code is given below:
#model FastFactsTestPortalMVCApp.Models.Administrator
#{
ViewBag.Title = "RegisterAdmin";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>RegisterAdmin</h2>
#using (Html.BeginForm("SaveRegisteredAdmin","Admin"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Administrator</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AdminId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminFirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminFirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminFirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminUserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminUserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminUserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminContactNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminContactNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminDesignation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminDesignation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminDesignation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminRoleId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.AdminRoleId, new SelectList(Model.Role.Administrators, "RoleId", "RoleName"), htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AdminRoleId, "", 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>
I basically wanted to Register a user with his/her role name, but which is a foreign key relationship. Since I tried many ways. I am not able to find the right method. I would love to have the support or guidance to understand the concept and correct my mistake too.
For the Register Admin, I created a View also, where the error exists.
The error in the view says Null after registering the or clicking on
the submit button. The null error was referred to DropDownList.
#Html.DropDownListFor(m => m.AdminRoleId, new SelectList(Model.Role.Administrators, "RoleId", "RoleName"), htmlAttributes: new { #class = "form-control" })
According to your description, I think the issue is related to above code, it uses Model binding method to bind the DropDownList, but in the RegisterAdmin Action method, we can see you are using ViewBag to store the roles, and didn't return the Administrator object. So, when you binding model to DropDownList, the Role is null, it will throw the null exception.
[AllowAnonymous]
public ActionResult RegisterAdmin()
{
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
ViewBag.RoleId = repObj.GetRoles();
return View();
}
To solve this issue, you could use the ViewBag to bind the DropDownList, code as below:
#Html.DropDownListFor(m => m.AdminRoleId, new SelectList(ViewBag.RoleId, "RoleId", "RoleName"), htmlAttributes: new { #class = "form-control" })
Note: Before return the view, you could check the ViewBag.RoleId, make sure it contain all roles.
The following code works well on my side, you could refer it:
[AllowAnonymous]
public ActionResult RegisterAdmin()
{
//FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
//ViewBag.RoleId = repObj.GetRoles();
List<Role> rolelist = new List<Role>()
{
new Role(){ RoleId =1001, RoleName="Admin"},
new Role(){ RoleId = 1002, RoleName="Developer"},
new Role(){RoleId = 1003, RoleName = "User"}
};
ViewBag.RoleId = rolelist;
return View();
}
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveRegisteredAdmin(Models.Administrator userObj)
{
if (ModelState.IsValid)
{
}
List<Role> rolelist = new List<Role>()
{
new Role(){ RoleId =1001, RoleName="Admin"},
new Role(){ RoleId = 1002, RoleName="Developer"},
new Role(){RoleId = 1003, RoleName = "User"}
};
ViewBag.Role = rolelist;
return View("RegisterAdmin");
}
The output as below:
I rectified the error using the following code in the view :
<div class="form-group">
#Html.LabelFor(model => model.AdminRoleId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.AdminRoleId, new SelectList(ViewBag.Rolelist, "RoleId", "RoleName"), htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AdminRoleId, "", new { #class = "text-danger" })
</div>
i have a create Actionresult method for Create view ,
public ActionResult Create()
{
Employee emp = new Employee();
StructureEntities db = new StructureEntities();
ViewBag.CityId = new SelectList(db.Cities, "CityId", "CityName");
ViewBag.RegionId = new SelectList(db.Regions, "RegionId", "RegionName");
return View(emp);
}
VIEW (Create),
<div class="form-group">
#Html.LabelFor(model => model.TribeId, "TribeId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TribeId", null, #Resource.SelectTribe,htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TribeId, "", new { #class = "text-danger" })
</div>
</div>
<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.Profile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<img src="#Url.Content(Model.Profile)" style="margin:5px" height="80" width="80" id="profilePreview" />
<input type="file" name="ProfileUpload" accept="image/jpeg, image/png" onchange="ShowImagePreview(this, document.getElementById('profilePreview'))" />
#Html.ValidationMessageFor(model => model.Profile, "", new { #class = "text-danger" })
</div>
</div>
Model (Employee) is,
[Display(Name = "TribeId", ResourceType = typeof(Resources.Resource))]
[Required(ErrorMessageResourceType = typeof(Resources.Resource),
ErrorMessageResourceName = "TribeIdRequired")]
public Nullable<int> TribeId { get; set; }
[Display(Name = "FirstName", ResourceType = typeof(Resources.Resource))]
[Required(ErrorMessageResourceType = typeof(Resources.Resource),
ErrorMessageResourceName = "FirstNameRequired")]
public string FirstName { get; set; }
public string Profile { get; set; }
[NotMapped]
public HttpPostedFileBase ProfileUpload { get; set; }
public Employee()
{
Profile = "~/AppFiles/Images/default.png";
}
Now issue is that if i do not pass "Employee" to view in Action method like,
return View();
I get Validation message for first name as well as for tribe, But if i pass model to view return View(emp); i do not get validation message for TribeId and while passing values for both firstname and Tribeid is NUll
Reason for passing model to view is i have default image profile that is populating from model until image is not selected.
How can i show validation message of tribeId by passing model to view.
Hopes for your suggestions.
I am new in ASP.NET and I am trying to decorate an action method to allow an administrator to create new user by inserting the first, last names and the balance. The action method should generates Id, account number and AppUserId in the checkingaccount table. However, the post Create action throws the following exception because I am not passing AppUserId
Validation failed for one or more entities. See
'EntityValidationErrors' property for more details.
Is there away I can make the AppuserId added on the table?
Create Action Method
[HttpPost]
public ActionResult Create(string FName, string LName, string UserId, decimal balance)
{
var accountNumber = (12 + db.checkAccounts.Count()).ToString().PadLeft(10, '0');
var checking = new CheckingAccount
{
FirstName = FName,
LastName = LName,
AccountNumber = accountNumber,
Balance = balance,
AppUserId = UserId
};
db.checkAccounts.Add(checking);
db.SaveChanges();
return RedirectToAction("ViewAccounts");
}
CheckingAccount Model
public class CheckingAccount
{
public int Id { get; set; }
public string AccountNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Telephone { get; set; }
public decimal Balance { get; set; }
public virtual ApplicationUser User { get; set; }
[Display(Name = "User ID: ")]
[Required]
public string AppUserId { get; set; }
}
CheckingAccount Model
#model Project.Models.CheckingAccount
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Checking Account</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.AccountNumber)
<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.Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Balance, "", new { #class = "text-danger" })
</div>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.AppUserId)
<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", "ViewAccounts", null, new { #class = "btn btn-info" })
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Your ActionMethod parameters much match exactly the names of the form fields. You are using FName and LName for instance when your actual model properties are FirstName and LastName. As a result, your parameters are empty strings. The model binder has no idea that FName and FirstName are supposed to be the same thing for instance.
Either correct your parameter names in your action method:
[HttpPost]
public ActionResult Create(string FirstName, string LastName, string AppUserId, decimal Balance){
OR
Since you are using strongly typed views, just use the model from your View as your Create ActionResult parameter
[HttpPost]
public ActionResult Create(CheckingAccount model){
//fancy black magic binds all of the form properties
//to this model parameter for you!
model.AccountNumber = (12 + db.checkAccounts.Count()).ToString().PadLeft(10, '0');
db.checkAccounts.Add(model);
db.SaveChanges();
}
Additionally, you can use the following code to get the specific entity errors:
try{
db.SaveChanges();
}
catch (DbEntityValidationException e){
foreach (var error in e.EntityValidationErrors){
foreach (var propertyError in error.ValidationErrors){
Console.WriteLine($"{propertyError.PropertyName} had the following issue: {propertyError.ErrorMessage}");
}
}
}
You could wrap your offending code with a try catch, with the in the catch to see the specific Entity Framework errors that you need to resolve. If you dont know what to do once you have the detailed errors post back here. But more information would be helpful.
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}