I have a aspx page in my view, which calls a partial view,
using (Html.BeginForm("Edit", "MyReport", FormMethod.Post, new { name = "myform", autocomplete = "off" }))
{%>
<%
Html.RenderPartial("_Form");%>
<% } %>
partial view is
<div>
<%=Html.ValidationSummary()%>
</div>
<div class="fieldRow">
<span class="fieldCell threeCol">
<label for="schedule.SavedReportName">
Name<span class="requiredField">*</span>
</label>
<%=Html.TextBox("schedule.SavedReportName", ViewData.Model.SavedReportName, new {style = "width:516px;"})%>
</span>
</div>
My model has this property
[Required(ErrorMessage = "Name is required.")]
[StringLength(60, ErrorMessage = "Maximum 60")]
public string SavedReportName { get; set; }
The problem I am getting is, I am able to see string length validation error twice.
What might be the problem?
Related
In ASP.NET Core MVC (and ASP.NET MVC too), the Html.ValidationSummary helper extension and the <div asp-validation-summary=""> tag-helper both only render the "short" Display Name of the invalid property.
This means that if a form/#model has sub-forms (all using the same sub-form class) with the same validation errors then the user sees unhelpfully ambiguous validation error messages in the summary.
For example, consider this (contrived) form class below:
public class NewCompanyAccountForm
{
[Display( Name = "Primary user" )]
public NewUserForm PrimaryUser { get; } = new NewUserForm();
[Display( Name = "Secondary user" )]
public NewUserForm SecondaryUser { get; } = new NewUserForm();
[Display( Name = "Tertiary user" )]
public NewUserForm TertiaryUser { get; } = new NewUserForm();
}
public class NewUserForm
{
[Required]
[Display( Name = "User name" )]
[RegularExpression( "^[a-z][0-9_a-z]+$" )]
[StringLength( 20 )]
public String? UserName { get; set; }
[Required]
[Display( Name = "Display name" )]
[StringLength( 50 )]
public String? DisplayName { get; set; }
}
And these views:
NewCompanyAccount.cshtml:
#model NewCompanyAccountForm
<div asp-validation-summary="All"></div>
<fieldset>
<legend>#Html.DisplayNameFor( m => m.PrimaryUser )</legend>
<partial name="NewUserForm" for="PrimaryUser"/>
</fieldset>
<fieldset>
<legend>#Html.DisplayNameFor( m => m.SecondaryUser )</legend>
<partial name="NewUserForm" for="SecondaryUser"/>
</fieldset>
<fieldset>
<legend>#Html.DisplayNameFor( m => m.TertiaryUser )</legend>
<partial name="NewUserForm" for="TertiaryUser "/>
</fieldset>
NewUserForm.cshtml:
#model NewUserForm
<div class="field">
#Html.LabelFor( m => m.UserName )
#Html.TextBoxFor( m => m.UserName )
#Html.ValidationMessageFor( m => m.UserName )
</div>
<div class="field">
#Html.LabelFor( m => m.DisplayName )
#Html.TextBoxFor( m => m.DisplayName )
#Html.ValidationMessageFor( m => m.DisplayName )
</div>
If someone submits an empty form, then the <div asp-validation-summary="All"></div> will render a list that looks like this:
<ul>
<li>The User name field is required</li>
<li>The Display name field is required</li>
<li>The User name field is required</li>
<li>The Display name field is required</li>
<li>The User name field is required</li>
<li>The Display name field is required</li>
</ul>
What I want is the validation summary to include the [Display( Name = "" )] of the parent form/model property for all ancestors going back up to the form/model root.
...so the user would see something like this:
<ul>
<li>The Primary User's User name field is required</li>
<li>The Primary User's Display name field is required</li>
<li>The Secondary User's User name field is required</li>
<li>The Secondary User's Display name field is required</li>
<li>The Tertiary User's User name field is required</li>
<li>The Tertiary User's Display name field is required</li>
</ul>
I can't see any obvious method or functionality built-in to ASP.NET MVC or ASP.NET Core for this - which is odd because functionality like this would be essential for forms using List<ChildForm>, for example.
I tried as below:
NewCompanyAccount.cshtml:
#model NewCompanyAccountForm
#{
ViewDataDictionary PrimaryUserViewData = new ViewDataDictionary(this.ViewData);
PrimaryUserViewData.Add("WhichUser", "PrimaryUser");
ViewDataDictionary SecondaryUserViewData = new ViewDataDictionary(this.ViewData);
SecondaryUserViewData.Add("WhichUser", "SecondaryUser");
ViewDataDictionary TertiaryUserViewData = new ViewDataDictionary(this.ViewData);
TertiaryUserViewData.Add("WhichUser", "TertiaryUser");
}
<form asp-controller="Home" asp-action="Test">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.PrimaryUser)</legend>
<partial name="NewUserForm" for="PrimaryUser" view-data="PrimaryUserViewData"/>
</fieldset>
<fieldset>
<legend>#Html.DisplayNameFor(m => m.SecondaryUser)</legend>
<partial name="NewUserForm" for="SecondaryUser" view-data="SecondaryUserViewData"/>
</fieldset>
<fieldset>
<legend>#Html.DisplayNameFor(m => m.SecondaryUser)</legend>
<partial name="NewUserForm" for="TertiaryUser " view-data="TertiaryUserViewData"/>
</fieldset>
<input type="submit" value="Submit" />
</form>
<style>
.field-validation-valid {
display: none;
}
.validation-summary-valid {
display: none;
}
</style>
pratial view:
#model NewUserForm
#{
var message = ViewData.ContainsKey("WhichUser") ? ViewData["WhichUser"].ToString() : "";
var usernamessage = string.Format("{0}'s User name field is required", message);
var displaynamessage = string.Format("{0}'s DisPlay name field is required", message);
}
<div class="field">
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName, usernamessage)
</div>
<div class="field">
#Html.LabelFor(m => m.DisplayName)
#Html.TextBoxFor(m => m.DisplayName)
#Html.ValidationMessageFor(m => m.DisplayName, displaynamessage)
</div>
Result:
I need to perform validation on a textbox and Dropdown which triggers only when both the values are empty and does nothing when one of the value is empty. How would i implement it? Do i need to create a custom validator? Below is my Model and View
Model
public class CustomValidators
{
[Required]
[Required(ErrorMessage = "State Required")]
public string drpStateId { set; get; }
public System.Web.Mvc.SelectList drpState { set; get; }
[Required(ErrorMessage ="Region Required")]
public string txtRegion { set; get; }
}
View
#model InterviewTest.Models.CustomValidators
#{
ViewBag.Title = "Custom Validator";
Layout = "~/Views/_Layout.cshtml";
}
<p>#Html.ActionLink("< Back", "Index")</p>
#using (Html.BeginForm("CustomValidatorPost"))
{
#Html.ValidationSummary()
<div class="container-fluid">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#Html.DropDownListFor(c => c.drpStateId, Model.drpState, "", new { #class = "form-control" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(x => Model.txtRegion, new { #class = "form-control" })
#*<input type="text" id="txtRegion" name="txtRegion" class="form-control" />*#
</div>
</div>
<div class="col-sm-3">
<button type="submit" name="btnSubmit" id="btnSubmit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}
There is no out of the box validation that works on 2 fields except for the compare validator, so in your case you have to create a custom validation.
You can create a JavaScript function and fire it on onchange on both the two text boxes and within it check the values and if both are empty, show an error message and prevent the form from being submitted, you can achieve that using JQuery validation by adding a custom validator, see this link for more details https://jqueryvalidation.org/jQuery.validator.addMethod/
On Server side, you can do a simple if statement in the controller action to validate that both the values are not empty and if both are empty, then add an error to the ModelState
I've got two forms on my page. My viewmodel looks like this:
public class HomeViewModel
{
[Required(ErrorMessage = "We kind of need an email address!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string Email { get; set; }
public ContactForm ContactForm { get; set; }
}
ContactForm:
public class ContactForm
{
[Required(ErrorMessage = "We need your name, please!")]
public string Name { get; set; }
[Required(ErrorMessage = "We need your email, please!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Please elaborate a little!")]
public string Message { get; set; }
}
First form action:
public ActionResult FreeConsultSubmit(HomeViewModel model)
{
if (ModelState.IsValid)
{
//do stuff
}
return PartialView("_SubmitResult", false);
}
Second Action:
public ActionResult ContactSubmit(HomeViewModel model)
{
if (ModelState.IsValid)
{
//dostuff
}
return PartialView("_SubmitContactResult", false);
}
First Ajax Form
#using (Ajax.BeginForm("FreeConsultSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "FreeConsultResults"
}))
{
<div id="FreeConsultResults">
<div class="row">
<div class="small-4 columns small-centered text-center splashEmail">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Please enter your email..." })
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="row">
<div class="small-5 columns small-centered text-center">
<input type="submit" class="hvr-border-fade splashCallToAction" value="Get Started" />
</div>
</div>
</div>
}
Second Ajax Form:
#using (Ajax.BeginForm("ContactSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ContactSubmitResults"
}))
{
<div id="ContactSubmitResults">
<div class="row">
<div class="small-12 columns small-centered">
#Html.TextBoxFor(m => m.ContactForm.Name, new { #placeholder = "Your Name" })
#Html.ValidationMessageFor(m => m.ContactForm.Name)
#Html.TextBoxFor(m => m.ContactForm.EmailAddress, new { #placeholder = "Your Email Address" })
#Html.ValidationMessageFor(m => m.ContactForm.EmailAddress)
#Html.TextAreaFor(m => m.ContactForm.Message, new { #placeholder = "Your Message", #class = "contactMessage" })
#Html.ValidationMessageFor(m => m.ContactForm.Message)
</div>
</div>
<div class="row">
<div class="small-12 columns small-centered text-center">
<a href="">
<input type="submit" class="hvr-border-fade sendMessageSmall" value="Send Message" />
</a>
</div>
</div>
</div>
}
I've got everything wired up fine, and client side validation works as it should. This may be overkill, but I also wanted to set up server side validation.
The issue is, when submitting the first form (just the email string), I check if the ModelState is valid, and it is. If you drill down into the ModelState, you see that only 1 property is being looked at.
If you submit the second form though (the ContactForm), the ModelState.IsValid returns false, and if you drill down, you see that it's looking at 4 properties (the 3 ContactForm properties, plus the string email). Since the email string is required, it fails.
I'm confused as to why it works for one, but not the other. I could just remove the server side validation, but I'd at least like to know why this is the case. I could also remove the error from the ModelState, but that doesn't seem elegant at all.
If you simply are trying to have two separate forms within one view, you're probably better off splitting the forms into separate "sub views" and child actions, and then using #Html.Action() to render them in place.
Here's an example:
Models
I'd remove the ContactForm model from HomeViewModel, and rename HomeViewModel to ConsultingForm (to match your naming convention for the contact model):
public class ConsultingForm
{
[Required(ErrorMessage = "We kind of need an email address!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string Email { get; set; }
}
public class ContactForm
{
[Required(ErrorMessage = "We need your name, please!")]
public string Name { get; set; }
[Required(ErrorMessage = "We need your email, please!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Please elaborate a little!")]
public string Message { get; set; }
}
Controller
Add "child" actions, like those below:
public class HomeController : Controller
{
public ActionResult Home()
{
return View();
}
[ChildActionOnly, HttpGet]
public ActionResult ConsultingRequest()
{
var model = new ConsultingForm();
return View(model);
}
[ChildActionOnly, HttpGet]
public ActionResult ContactRequest()
{
var model = new ContactForm();
return View(model);
}
}
The ChildActionOnlyAttribute marks the action as a child action. From the MSDN:
A child action method renders inline HTML markup for part of a view
instead of rendering a whole view.
Views
Your first subview will be the same as you already have:
#using (Ajax.BeginForm("FreeConsultSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "FreeConsultResults"
}))
{
<div id="FreeConsultResults">
<div class="row">
<div class="small-4 columns small-centered text-center splashEmail">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Please enter your email..." })
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="row">
<div class="small-5 columns small-centered text-center">
<input type="submit" class="hvr-border-fade splashCallToAction" value="Get Started" />
</div>
</div>
</div>
}
Your second subview simply needs to remove the extra "step" in the property bindings:
#using (Ajax.BeginForm("ContactSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ContactSubmitResults"
}))
{
<div id="ContactSubmitResults">
<div class="row">
<div class="small-12 columns small-centered">
#Html.TextBoxFor(m => m.Name, new { #placeholder = "Your Name" })
#Html.ValidationMessageFor(m => m.Name)
#Html.TextBoxFor(m => m.EmailAddress, new { #placeholder = "Your Email Address" })
#Html.ValidationMessageFor(m => m.EmailAddress)
#Html.TextAreaFor(m => m.Message, new { #placeholder = "Your Message", #class = "contactMessage" })
#Html.ValidationMessageFor(m => m.Message)
</div>
</div>
<div class="row">
<div class="small-12 columns small-centered text-center">
<a href="">
<input type="submit" class="hvr-border-fade sendMessageSmall" value="Send Message" />
</a>
</div>
</div>
</div>
}
The "wrapper", or parent view, will look something like:
<div class="whatever">
#Html.Action("ConsultingRequest", "Home")
#Html.Action("ContactRequest", "Home")
</div>
If you inspect the rendered HTML, you'll see that each form is properly bound to only its model's properties, so when you post each form, only those properties are model-bound and validated.
I have what I think is a easy problem but for the life of me I cant figure it out. I have a form which imports many emails from a multi-line text box. From that import, I generate a report that tells the user the status of the imported emails and any errors. I can generate the report data fine, but cant seem to display the "Errors" field properly in the view. The problem appears to be, the editor template for the "Errors" field, is not being used. My question is, how do I get the view to use and render the editor template for the "Errors" field. I have tried using UIHint, but it doesn't work. Any help would be appreciated.
ViewModels.cs
//**************************Report View Models***************************************
public class ShowErrors
{
public string EmailAddress { get; set; }
public string ErrorDescription { get; set; }
}
public class ReportViewModel
{
public int TotalEmails { get; set; }
public int SuccessEmails { get; set; }
public int DuplicateEmails { get; set; }
public int InvalidEmails { get; set; }
[UIHint("ShowErrors")]
public virtual ICollection<ShowErrors> Errors { get; set; }
}
public static class ViewModelHelpers
{
//*************************ReportViewModel Helpers**************************************
public static ShowErrors ShowErrors_ViewModel_To_Domain(this ShowErrors item)
{
var showErrors = new ShowErrors
{
EmailAddress = item.EmailAddress,
ErrorDescription = item.ErrorDescription
};
return (showErrors);
}
}
Controller for the Report:(Dont think the problem is here, I can generate the data for the report, just cant display it properly.
public ActionResult Import_Report(EmailEditViewModel emailEditViewModel)
{
string emailAddress = null;
string[] emailArray = Request.Form["ImportEmails"].Split (new string[] { System.Environment.NewLine }, StringSplitOptions.None);
var entityModified = new EmailContact();
var reportViewModel = new ReportViewModel();
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$"); //Regular Expression that checks email address is valid
List<ShowErrors> errorList = new List<ShowErrors>();
foreach (string item in emailArray)
{
ShowErrors errorItem = new ShowErrors();
emailAddress = item.Trim();
reportViewModel.TotalEmails += 1;
Match match = regex.Match(emailAddress); //Check email is in valid format
if (emailAddress == null || emailAddress == "")
{
reportViewModel.TotalEmails -= 1;
}
else if (!match.Success)
{
//Log this email as duplicate
reportViewModel.InvalidEmails += 1;
errorItem.EmailAddress = emailAddress;
errorItem.ErrorDescription = "Invalid Email";
errorList.Add(errorItem);
}
else if (_globalClasses.IsDuplicateEmail(emailAddress) > 0)
{
//Log this email as duplicate
reportViewModel.DuplicateEmails += 1;
errorItem.EmailAddress = emailAddress;
errorItem.ErrorDescription = "Duplicate Email";
errorList.Add(errorItem);
}
else
{
entityModified.EmailAddress = emailAddress;
entityModified.ActiveCampaigns = entityModified.Campaigns.Count(); //Calculates how many campaigns a contact is a member
try
{
db.EmailContacts.Add(_crypto.EncryptAndSanitizeEmailContacts(entityModified));
db.SaveChanges();
reportViewModel.SuccessEmails += 1;
AddOrUpdateEmailContacts(entityModified, emailEditViewModel.Campaigns); //Saves campaigns selected to this contact
db.SaveChanges();
//return RedirectToAction("Contact_List");
}
catch { }
}
}
reportViewModel.Errors = errorList;
return View(reportViewModel);
}
Here is the View:
#model HoltsCA.ViewModels.ReportViewModel
#{
ViewBag.Title = "Import_Report";
Layout = "~/Views/Shared/_LayoutDashboard.cshtml";
}
<fieldset>
<legend></legend>
<div class="row col-md-6">
<div id="bootstrapTableHeader" class="row">
<div class="col-sm-12">
<h2 style="text-align:center; color:#fff; font-size:1.3em;">Import Contacts Report</h2>
</div>
</div>
<div id="bootstrapTableRow" class="row">
<div class="col-sm-7" style="text-align:right">Total Emails:</div>
<div class="col-sm-5" style="text-align:left">#Html.DisplayFor(model => model.TotalEmails)</div>
</div>
<div id="bootstrapTableRow" class="row">
<div class="col-sm-7" style="text-align:right">Success Imported Emails:</div>
<div class="col-sm-5" style="text-align:left">#Html.DisplayFor(model => model.SuccessEmails)</div>
</div>
<div id="bootstrapTableRow" class="row">
<div class="col-sm-7" style="text-align:right">Duplicate Emails:</div>
<div class="col-sm-5" style="text-align:left">#Html.DisplayFor(model => model.DuplicateEmails)</div>
</div>
<div id="bootstrapTableRow" class="row">
<div class="col-sm-7" style="text-align:right">Invalid Emails:</div>
<div class="col-sm-5" style="text-align:left">#Html.DisplayFor(model => model.InvalidEmails)</div>
</div>
<div class="row" style="height:50px"></div>
<div id="bootstrapTableHeader" class="row">
<div class="col-sm-12">
<h2 style="text-align:center; color:#fff; font-size:1.3em;">Error Report</h2>
</div>
</div>
<div id="bootstrapAccentRow" class="row">
<div class="col-sm-6" style="text-align:left">
<b>Email Address</b>
</div>
<div class="col-sm-6" style="text-align:left">
<b>Error Description</b>
</div>
</div>
<div id="bootstrapRow" class="row">
#Html.DisplayFor(model => model.Errors)
</div>
</div>
</fieldset>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
Finally Here is the Editor Template ShowErrors.cshtml
#model ShowErrors
#using HoltsCA.ViewModels
<fieldset>
<div class="col-md-6" style="text-align:left;">
#Html.DisplayFor(model => model.EmailAddress)
</div>
<div class="col-md-6" style="text-align:left;">
#Html.DisplayFor(model => model.ErrorDescription)
</div>
</fieldset>
I think you are trying to display errors by using editor template. Put your error template inside DisplayTemplates folder under Shared folder.
If you are using #Html.DisplayFor then your template should be in the DisplayTemplates folder and similar logic while displaying editing template. To specify which template to use you can also do
#Html.DisplayFor(model => model.Errors, "ShowErrors")
Another thing is your model.Errors is a List<ShowErrors> and inside your display template you have just #model ShowErrors instead you should display it like IEnumerable<ShowErrors> and iterate in the template to show all the errors.
#model IEnumerable<ShowErrors>
#using HoltsCA.ViewModels
#foreach(var error in Model)
{
<div class="col-md-6" style="text-align:left;">
#Html.DisplayFor(error => error.EmailAddress)
</div>
<div class="col-md-6" style="text-align:left;">
#Html.DisplayFor(error => error.ErrorDescription)
</div>
}
That's not an EditorTemplate, it's a DisplayTemplate.
You just need to create a folder named "DisplayTemplates" under Views/Shared, and put the ShowErrors.cshtml partial view in the folder.
Your model is a List<ShowErrors> not a ShowError object.
You could change your view to this:
#model List<ShowErrors>
#using HoltsCA.ViewModels
#foreach(var error in Model)
{
<fieldset>
<div class="col-md-6" style="text-align:left;">
#Html.DisplayFor(error => error .EmailAddress)
</div>
<div class="col-md-6" style="text-align:left;">
#Html.DisplayFor(error => error .ErrorDescription)
</div>
</fieldset>
i'm having issues with implementing a ViewModel class which acts as a wrapper class around a Model class called "User" generated by L2SQL. In short, I have two instances when i have to validate against the L2SQL model. One when the user first signs up, and the second when the user logs in and edits only part of his account data.
The initial "problem" was when trying to edit & validate only some the account details against the original L2SQL model from a View which only displays the few (e.g FirstName, LastName, Email), the missing ones (e.g. Password) would flair up when validation was run. The Password settings will have its own View.
I was advised here on StackOverflow that adding a wrapping ViewModel class would be the best solution. So I did, implemented below:
ViewModel code:
[Bind]
public class AccountEdit
{
public User UserAccount { get; set; }
[Required(ErrorMessage = "First name required"), StringLength(20, MinimumLength = 3, ErrorMessage = "Must be between 3 and 20 characters")]
public string FirstName { get { return UserAccount.FirstName; } set { UserAccount.FirstName = value; } }
[Required(ErrorMessage = "Last name required"), StringLength(20, MinimumLength = 3, ErrorMessage = "Must be between 3 and 20 characters")]
public string LastName { get { return UserAccount.LastName; } set { UserAccount.LastName = value; } }
[Required(ErrorMessage = "Email address required"), RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage = "Must be a valid email address")]
public string Email { get { return UserAccount.Email; } set { UserAccount.Email = value; } }
}
Controller code:
//
// GET /User/Account
public ActionResult Account()
{
string cookieUser = User.Identity.Name;
User user = userRepository.GetUserByEmail(cookieUser);
return View(user);
}
// POST /User/Account
[HttpPost]
public ActionResult Account(AccountEdit model)
{
if (ModelState.IsValid)
{
model.LastUpdated = DateTime.Now;
userRepository.Save();
}
return View(model);
}
Veiw code:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/User.Master" Inherits="System.Web.Mvc.ViewPage<Digitalent.Models.User>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Account settings
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary("Oops! Please correct the errors and try again!") %>
<p>
<label for="FirstName">First name:</label>
<%: Html.TextBoxFor(model => model.FirstName, new { #class = "textfield" })%>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</p>
<p>
<label for="LastName">Last name:</label>
<%: Html.TextBoxFor(model => model.LastName, new { #class = "textfield" })%>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</p>
<p>
<label for="Email">Email address:</label>
<%: Html.TextBoxFor(model => model.Email, new { #class = "textfield" })%>
<%: Html.ValidationMessageFor(model => model.Email) %>
</p>
<p>
Email newsletter: <%= Html.CheckBoxFor(model => model.EmailNewsletter) %>
<label for="EmailNewsletter">Keep me posted with latest Digitalent happenings.</label>
</p>
<p>
<input type="submit" value="Save changes" class="button" />
</p>
<p>Change your password settings</p>
<% } %>
But now when i tried to run the app i get an error when it runs the validation:
'Object reference not set to an instance of an object.'
On the line below in my ViewModel:
'public string FirstName { get { return UserAccount.FirstName; } set { UserAccount.FirstName = value; } }'
Where am I going wrong or can anyone else tell me a better recommended approach as i'm a novice. Help please!
Change your view from:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/User.Master"
Inherits="System.Web.Mvc.ViewPage<Digitalent.Models.User>" %>
to:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/User.Master"
Inherits="System.Web.Mvc.ViewPage<Digitalent.Models.AccountEdit>" %>