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>
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 have a fairly simple form and ViewModel which works fine, but when I add this JS, the form no longer submits to the controller:
$("#crmtForm").submit(function (e) {
console.log('submit');
});
Why? I'm pretty sure this is supposed to work... Please can someone help this makes no sense.
Controller
[HttpPost]
public async Task<ActionResult> Create(CRMTItemViewModel viewModel)
{
viewModel.CreatedBy = System.Security.Claims.ClaimsPrincipal.Current.Claims.FirstOrDefault(c => c.Type == "name").Value;
if (viewModel.ProjectTitle == "spinnertest")
return View();
// Insert db rows?
var crmtItem = await crmtItemsManager.InsertItem(viewModel);
// Initialise workspace on a seperate thread
new Thread(() =>
{
var projectManager = new ProjectManager();
projectManager.ProcessRequest(crmtItem);
}).Start();
// Redirect to item
return RedirectToAction("Details", new { id = crmtItem.Id });
}
Form
#using (Html.BeginForm("Create", "CrmtItems", FormMethod.Post, new { id = "crmtForm" }))
{
<div class="form-horizontal">
<h4>New Project Workspace Form</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProjectTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProjectTitle, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.ProjectTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProjectStage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.ProjectStage, new { #class = "form-control", required = "required" })
#Html.ValidationMessageFor(model => model.ProjectStage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CRMTNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CRMTNumber, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.CRMTNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GbSNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GbSNumber, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.GbSNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Confidential, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Confidential, new { #class = "form-control", #style = "height:17px;" })
#Html.ValidationMessageFor(model => model.Confidential, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => Model.SelectedTags, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(m => m.Id, new { required = "required" })
#Html.ListBoxFor(m => m.SelectedTags, new SelectList(users, "UserName", "DisplayName"), new { #class = "teamSelecter", name = "states[]", multiple = "multiple", style = "display:none; width:100%;", required = "required" })
#Html.ValidationMessageFor(model => model.SelectedTags, "", new { #class = "text-danger" })
<p id="pmWarning" class="text-danger" hidden>Please select one or more project managers</p>
</div>
</div>
<br />
<button id="formSubmit" class="btn btn-default btn-lg pull-right" type="submit" value="submit">Submit</button>
<div class="loader pull-right" hidden></div>
</div>
}
ViewModel
public class CRMTItemViewModel
{
public int Id { get; set; }
[Display(Name = "Project Title")]
[Remote("DoesProjectTitleExist", "CRMTItems", HttpMethod = "POST",
ErrorMessage = "Workspace for that project title already exists.")]
public string ProjectTitle { get; set; }
[Display(Name = "Project Stage")]
public ProjectStage? ProjectStage { get; set; }
[Display(Name = "CRMT Number")]
[Remote("DoesCrmtNumberExist", "CRMTItems", HttpMethod = "POST",
ErrorMessage = "Workspace for that CRMT number already exists.")]
public int? CRMTNumber { get; set; }
[Display(Name = "GBS Number")]
[Remote("DoesGbSNumberExist", "CRMTItems", HttpMethod = "POST",
ErrorMessage = "Workspace for that GBS project number already exists.")]
public int? GbSNumber { get; set; }
public bool Confidential { get; set; }
[Display(Name = "Project Managers")]
public IEnumerable<string> SelectedTags { get; set; }
}
I tried your code in my project its working,may be issue with your jquery version,one more thing I found when I was created scaffolding view with this model it automatically created #section Scripts {
#Scripts.Render("~/bundles/jqueryval")
} at end of view page,
when I removed this script from page then able to call post method otherwise not.
I have a partial view that returns a list of users address's, I need the user to be able to select one, then when they press "submit" along with the other details it takes the details from the selected address returns it to the controller, from there I know how to assign it where I want. How would I do this? Examples and help appreciated
Here is my controller for creating the order, view beneath;
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values, string id)
{
var order = new Order();
TryUpdateModel(order);
//sets date and username
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Order gets saved
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Order gets processed
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
//Save again, total not saving properly until now
storeDB.SaveChanges();
return RedirectToAction("Complete",
new { id = order.OrderId });
}
VIEW
#model T_shirt_Company_v3.Models.Order
#{
ViewBag.Title = "Address And Payment";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.OrderId)
#Html.HiddenFor(x => x.OrderDate)
#Html.HiddenFor(x => x.PaymentTransactionId)
#Html.HiddenFor(x => x.Total)
#Html.HiddenFor(x => x.Username)
<div class="form-horizontal">
<h2>Address And Payment</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#{Html.RenderAction("Listofaddresses", "Checkout");}
<h2>Select Postage type</h2>
#Html.EnumDropDownListFor(model => model.PostageList, "-- Please select postage type --")
<h2>Payment</h2>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.FullName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.FullName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.FullName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.CardNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.CardNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.CardExpireMonth, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="row">
<div class="col-md-1">
#Html.EditorFor(model => model.cardDetails.CardExpireMonth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardExpireMonth, "", new { #class = "text-danger" })
</div>
<div class="col-md-1">
#Html.EditorFor(model => model.cardDetails.CardExpireYear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardExpireYear, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.Cvc, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.Cvc, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.Cvc, "", 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>
}
Partial View
#model IEnumerable<T_shirt_Company_v3.Models.deliveryAddress>
#foreach (var item in Model)
{
<div style="width: 180px">
<div class="thumbnail">
<p>#Html.DisplayFor(modelItem => item.FirstName) #Html.DisplayFor(modelItem => item.LastName) </p>
<p>#Html.DisplayFor(modelItem => item.Address)</p>
<p>#Html.DisplayFor(modelItem => item.City)</p>
<p>#Html.DisplayFor(modelItem => item.PostalCode)</p>
<p>#Html.DisplayFor(modelItem => item.Country)</p>
</div>
</div>
}
Address Class
public class deliveryAddress
{
[Key]
[ScaffoldColumn(false)]
public int AdressId { get; set; }
[ScaffoldColumn(false)]
public string UsersAddress { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Your name is too long")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
[StringLength(16, ErrorMessage = "Last name is too long.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Postcode is required.")]
[Display(Name = "Post Code")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Phone home number is required.")]
[Display(Name = "Home Telephone")]
public string Phone { get; set; }
[Required(ErrorMessage = "Phone mobile number is required.")]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
}
}
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 want to make a DropDownList with a numeric rating from 1-5. I have a rating model and I want to apply these dropdown values to WaitTime, Attentive and Outcome.
Can I just set these values in the view and use the model? If so how would i go about doing this?
My Model Class:
public class Ratings
{
//Rating Id (PK)
public int Id { get; set; }
public string UserId { get; set; }
//Medical Practice (FK)
public int MpId { get; set; }
public MP MP { get; set; }
//User ratings (non-key values)
[Required] //Adding Validation Rule
public int WaitTime { get; set; }
[Required] //Adding Validation Rule
public int Attentive { get; set; }
[Required] //Adding Validation Rule
public int Outcome { get; set; }
}
My View:
<div class="form-group">
#Html.LabelFor(model => model.WaitTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.WaitTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WaitTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Attentive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Attentive, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Attentive, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Outcome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Outcome, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Outcome, "", new { #class = "text-danger" })
</div>
</div>
Use this instead of EditorFor for each field:
#Html.DropDownListFor(model => model.Outcome, new SelectList(Enumerable.Range(1, 5)))
Here is the working fiddle - https://dotnetfiddle.net/daB2DI
In short, lets say your model is -
public class SampleViewModel
{
[Required] //Adding Validation Rule
public int WaitTime { get; set; }
[Required] //Adding Validation Rule
public int Attentive { get; set; }
[Required] //Adding Validation Rule
public int Outcome { get; set; }
}
And your controller actions are -
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
[HttpPost]
public JsonResult PostData(SampleViewModel model)
{
return Json(model);
}
Your Get CSHTML should be -
#model HelloWorldMvcApp.SampleViewModel
#{
ViewBag.Title = "GetData";
}
<h2>GetData</h2>
#{
var items = new List<SelectListItem>();
for (int i = 1; i < 6; i++)
{
var selectlistItem = new SelectListItem();
var code = 0;
selectlistItem.Text = (code + i).ToString();
selectlistItem.Value = (code + i).ToString();
items.Add(selectlistItem);
}
}
#using (Html.BeginForm("PostData","Home"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SampleViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.WaitTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.WaitTime, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WaitTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Attentive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Attentive, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Attentive, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Outcome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Outcome, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Outcome, "", 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>
}
When you run the code, you should see page like below -
And when you select some values and click on create, you should get those values in PostData action.
try to adapt this to your project
in your controller:
ViewBag.ParentID = new SelectList(departmentsQuery, "NewsMID", "Title", selectedDepartment);
return View(model);
in your view put this
#Html.DropDownList("ParentID")