Exception Model.Questions null in mvc 3 view - c#

I am working on mvc - 3. I have created a register model and a register view.
Register view :
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.ConfirmPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.ConfirmPassword)
#Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Question)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Question, new SelectList(Model.Questions))
#Html.HiddenFor(m => m.Questions)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Answer)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Answer)
#Html.ValidationMessageFor(m => m.Answer)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
}
Register Model
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[RegularExpression(#"^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$", ErrorMessage="Invalid email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Security question")]
public string Question { get; set; }
[Display(Name = "Security question")]
public List<string> Questions { get; set; }
[Display(Name = "Security answer")]
public string Answer { get; set; }
}
My issue is when we submit the register form to server than all data will send to server except questions list. So if validation fails than i am getting the exception Model.Questions is null. How can i solve this issue ?

Look at my example and you will understand how it works:
#{
List<string> test = new List<string> { "111", "222", "333" };
}
<div id="test1">
#Html.HiddenFor(x => test)
</div>
<div id="test2">
#for (int i = 0; i < test.Count; i++)
{
#Html.HiddenFor(x => test[i])
}
</div>
Will render:
<div id="test1">
<input id="test" name="test" type="hidden" value="System.Collections.Generic.List`1[System.String]" />
</div>
<div id="test2">
<input id="test_0_" name="test[0]" type="hidden" value="111" />
<input id="test_1_" name="test[1]" type="hidden" value="222" />
<input id="test_2_" name="test[2]" type="hidden" value="333" />
</div>

You need to either serialize the list to a hidden form field, or make sure you reload the list before your return View(model);

Try this
public ActionResult SomeAction(RegisterModel model)
{
if(ModelState.IsValid)
{
// perform the functionality when Mmodel is Valid
return View(model);
}
// bind data to Question list if model is fail
model.Questions = new List<String>();
return View(model);
}
NOTE: you need to bind the data to Question List when your model validation is fail before returning View.

Related

ASP .NET MVC 5 Html.ValidationMessageFor not working

Following is .cshtml code:
using (Ajax.BeginForm("UploadEdit", "Widget", new { Type = "SampleSurvey" }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "SampleSurvey-widget", LoadingElementId = "report-loader", OnBegin = "$('#report-loader').show();", OnSuccess = "$('#report-loader').hide();" }, new { enctype = "multipart/form-data", id = "SampleSurvey" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Type)
#Html.HiddenFor(model => model.IsDealer)
#Html.HiddenFor(model => model.Filter)
<div class="form form--searchcriteria">
<fieldset class="">
<div class="field_group">
<div class="field">
#Html.LabelFor(Model => Model.FirstName, new { #class = "field__label" })
<div class="field__controls">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="field">
#Html.LabelFor(model => model.LastName, new { #class = "field__label" })
<div class="field__controls">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<div class="field">
#Html.LabelFor(model => model.Email, new { #class = "field__label" })
<div class="field__controls">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
</div>
</fieldset>
<div class="form-control">
<button id="btnSubmit" class="btn icon icon-location-arrow" type="submit" onclick="$('#report-loader').show();">Send invitation</button>
</div>
</div>
}
And following is my model:
public class SampleSurvey : WidgetBase
{
[Required]
[StringLength(100, ErrorMessage = "Maximum 100 characters are allowed in field")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Maximum 100 characters are allowed in field")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid field.")]
[Display(Name = "Email Address")]
public string Email { get; set; }
}
But still validation is not working upon clicking the submit button, help will highly be appreciated.

'User' doesn't contain a definition in my Public Action Result

been making a database to store users details when they register and have a login/logout page. All was going dandy until when the database updates in the 'UserController' and I get this error:
> 'Mvcflight.RegistrationEntities' does not contain a definition for
> 'User' and no extension method 'User' accepting a first argument of
> type 'Mvcflight.RegistrationEntities' could be found (are you missing
> a using directive or an assembly reference?)
Of course nothing happens on the actual website and nothing saves to the database.
public ActionResult Register(User U)
{
using (RegistrationEntities dc = new RegistrationEntities())
if (ModelState.IsValid)
{
//you should check duplicate registration here
dc.User.Add(U);
dc.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message = "Successfully Registration Done";
}
return View(U);
}
The database can't update I don't know why, any ideas?
Here's my class:
public class User
{
public int Id { get; set; }
[Required(ErrorMessage = "Please provide username", AllowEmptyStrings = false)]
public string userName { get; set; }
[Required(ErrorMessage = "Please provide Password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[StringLength(50, MinimumLength = 8, ErrorMessage = "Password must be 8 char long.")]
public string userPassword { get; set; }
[Compare("Password", ErrorMessage = "Confirm password dose not match.")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Please provide full name", AllowEmptyStrings = false)]
public string fullName { get; set; }
[RegularExpression(#"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+#(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",
ErrorMessage = "Please provide valid email id")]
public string userEmail { get; set; }
}
And my HTML code:
<h2>Register</h2>
#model Mvcflight.Models.User
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
#Html.AntiForgeryToken()
#if (ViewBag.Message != null)
{
<div style="border:solid 1px green">
#ViewBag.Message
</div>
}
<div class="editor-label">
#Html.LabelFor(model => model.userName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userName)
#Html.ValidationMessageFor(model => model.userName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.userEmail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userEmail)
#Html.ValidationMessageFor(model => model.userEmail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.userPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userPassword)
#Html.ValidationMessageFor(model => model.userPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.fullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.fullName)
#Html.ValidationMessageFor(model => model.fullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Id)
#Html.ValidationMessageFor(model => model.Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
To note I have another database on the website, both sharing my 'FlightClass'
Thanks for any and all help, let me know if you need more info/code!!
:)

MVC ValidationMessageFor not working properly

I have the following in my view:
<fieldset>
<legend>User Registration</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UsrName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UsrName)
#Html.ValidationMessageFor(m => m.UsrName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Pwd)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Pwd)
#Html.ValidationMessageFor(m => m.Pwd)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.ReEnterPwd)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.ReEnterPwd)
#Html.ValidationMessageFor(m => m.ReEnterPwd)
</div>
<fieldset>
<legend>Location</legend>
<span id="locationDiv">
#Html.RadioButtonFor(m => m.Location, "Loc1") #Html.Label("Loc1")
</span>
#Html.RadioButtonFor(m => m.Location, "Loc2") #Html.Label("Loc2")
#Html.ValidationMessageFor(m => m.Location)
</fieldset>
<fieldset>
<legend>Role</legend>
#Html.RadioButtonFor(m => m.Role, "User") #Html.Label("User")
#Html.RadioButtonFor(m => m.Role, "Admin") #Html.Label("Admin")
#Html.ValidationMessageFor(m => m.Role)
</fieldset>
<p>
<input type="submit" value="Register User" />
</p>
</fieldset>
Even if I don't have all the fields filled, it still goes to the controller even though they are all required. I thought
#Html.ValidationMessageFor
was supposed to prevent that.
[Required]
public string Location { get; set; }
[Required]
public string Role { get; set; }
[Required]
[Display(Name = "User Name")]
public string UsrName { get; set; }
[Required]
[StringLength(50, MinimumLength = 5, ErrorMessage = "Must have a minimum length of 5.")]
public string Pwd { get; set; }
[Required]
[Display(Name = "Re-enter Password")]
[StringLength(50, MinimumLength = 5, ErrorMessage = "Must have a minimum length of 5.")]
[Compare("Pwd", ErrorMessage = "The password and re-entered password do not match.")]
public string ReEnterPwd { get; set; }
You must include the following scripts in the view:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
I had to include the JQuery Validation bundle at the bottom of my view in the scripts section.
I noticed this exists in all the baked in views for login and authentication but needs to be manually added to your custom views.
Example
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
}

MVC3 validation problems

I have the following view, which fails to validate on Title, and NewsContent. Title validation works but not NewsContent. How can i fix it.
#model Foo.NewsViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<fieldset>
<legend>Category Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.News.Title)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.News.Title)
#Html.ValidationMessageFor(m => m.News.Title)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.NewsContent)
</div>
<div class="editor-field" id="container">
#Html.TextAreaFor(m => m.News.NewsContent)
#Html.ValidationMessageFor(m => m.News.NewsContent)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.Thumbnail)
</div>
<div class="editor-field">
<input type="file" name="files" id="thumbnail" />
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.Image)
</div>
<div class="editor-field">
<input type="file" name="files" id="original" />
</div>
<div class="editor-label">
#Html.Label("SelectedCategoryId")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories)
</div>
<div class="editor-label">
Publish
</div>
<div class="editor-field">
#Html.CheckBoxFor(m => m.News.Published, new { #checked = "checked" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</div>
}
and here is the model|:
public class News : IStorable
{
[Required]
[Display(Name = "Title")]
public virtual string Title { get; set; }
[Required]
[Display(Name = "Content")]
public virtual string NewsContent { set; get; }
......
Issue: Title validation works but not NewsContent.
Validations is not work, because of using Html.TextAreaFor() helper to render the "NewsContent" property,
Here is the code to make it work:
Change your model as:
Decorate the 'NewsContent' property with [DataType] attribute and set the data type as 'MultilineText'. This will indicates that the editor for this property should be a multi-line text input.
public class News : IStorable
{
[Required]
[Display(Name = "Title")]
public virtual string Title { get; set; }
[Required()]
[Display(Name = "Content")]
[DataType(DataType.MultilineText)]
public virtual string NewsContent { set; get; }
//....
}
In the view use Html.EditorFor() helper instead of Html.TextAreaFor() for the 'News.NewsContent' property.
//....
<div class="editor-label">
#Html.LabelFor(m => m.News.NewsContent)
</div>
<div class="editor-field" id="container">
#*#Html.TextAreaFor(m => m.News.NewsContent)*#
#Html.EditorFor(m => m.News.NewsContent)
#Html.ValidationMessageFor(m => m.News.NewsContent)
</div>
//....

Data in Form not Emailed - MvcMailer

I am trying to send the contents of a form with MvcMailer in my MVC 3 web application. The email sends, but it does not populate with the data from the form.
Here is the view of my form:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div id="section_1" class="section">
<p style="color:#e93738;display:none"></p>
<img src="/Content/1.png" id="one" class="step" alt="Step 1"/>
<h3>Personal Details of Student</h3>
<p>
<em>Please enter your personal details.</em><br />
</p>
<br />
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantFirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantFirstName)
#Html.ValidationMessageFor(model => model.ApplicantFirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantLastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantLastName)
#Html.ValidationMessageFor(model => model.ApplicantLastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantBirthDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantBirthDate)
#Html.ValidationMessageFor(model => model.ApplicantBirthDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantCellphoneNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantCellphoneNumber)
#Html.ValidationMessageFor(model => model.ApplicantCellphoneNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantEmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantEmailAddress)
#Html.ValidationMessageFor(model => model.ApplicantEmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PostalNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PostalNumber)
#Html.ValidationMessageFor(model => model.ApplicantEmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantSuburb)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantSuburb)
#Html.ValidationMessageFor(model => model.ApplicantSuburb)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantCity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantCity)
#Html.ValidationMessageFor(model => model.ApplicantCity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicationPostalCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicationPostalCode)
#Html.ValidationMessageFor(model => model.ApplicationPostalCode)
</div>
</div>
<div id="section_2" class="section">
<img src="/Content/2.png" id="two" class="step" alt="Step 2"/>
<h3>Parent Details</h3>
<p>
<em>Please enter your parent or guardian's details.</em><br />
</p>
<div class="editor-label">
#Html.LabelFor(model => model.ParentFirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentFirstName)
#Html.ValidationMessageFor(model => model.ParentFirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentLastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentLastName)
#Html.ValidationMessageFor(model => model.ParentLastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentEmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentEmailAddress)
#Html.ValidationMessageFor(model => model.ParentEmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentPostalNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentPostalNumber)
#Html.ValidationMessageFor(model => model.ParentPostalNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentSuburb)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentSuburb)
#Html.ValidationMessageFor(model => model.ParentSuburb)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentCity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentCity)
#Html.ValidationMessageFor(model => model.ParentCity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentPostalCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ParentPostalCode)
#Html.ValidationMessageFor(model => model.ParentPostalCode)
</div>
</div>
<a href='#Url.Action("SendApplication", "Home")'><input type="submit" value="Submit" /></a>
}
Here is part of my controller:
private IApplicationMailer _applicationMailer = new ApplicationMailer();
public IApplicationMailer ApplicationMailer
{
get { return _applicationMailer; }
set { _applicationMailer = value; }
}
public ActionResult SendApplication(Application application)
{
ApplicationMailer.Application(application).Send();
//Send() extension method: using Mvc.Mailer
return RedirectToAction("Index");
}
Here is my ApplicationMailer.cs:
public virtual MailMessage Application(Application application)
{
var mailMessage = new MailMessage{Subject = "Application"};
mailMessage.To.Add("amecily#gmail.com");
ViewBag.Data = "Debbie";
ViewBag.FirstName = application.ApplicantFirstName;
ViewBag.LastName = application.ApplicantLastName;
PopulateBody(mailMessage, viewName: "Application");
return mailMessage;
}
My IApplicationMailer.cs:
public interface IApplicationMailer
{
MailMessage Application(Application application);
}
And my Application.cshtml:
#model DFPProductions_Default.Models.Application
Hi #ViewBag.Data
A new application has been received:
#ViewBag.FirstName
#ViewBag.LastName
EDIT:
At the top of the view containing the form, I have:
#model DFPProductions_Default.Models.Application
And the Application.cs is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace DFPProductions_Default.Models
{
public class Application
{
[Required]
[Display(Name = "First Name")]
public string ApplicantFirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string ApplicantLastName { get; set; }
[Display(Name = "Birth Date")]
public DateTime ApplicantBirthDate { get; set; }
[Required]
[Display(Name = "Cellphone Number")]
public string ApplicantCellphoneNumber { get; set; }
[Display(Name = "Postal Address")]
public string PostalNumber { get; set; }
[Display(Name = "Suburb")]
public string ApplicantSuburb { get; set; }
[Display(Name = "City")]
public string ApplicantCity { get; set; }
[Display(Name = "Post Code")]
public string ApplicationPostalCode { get; set; }
[Required]
[Display(Name = "Email Address")]
public string ApplicantEmailAddress { get; set; }
[Display(Name = "First Name")]
public string ParentFirstName { get; set; }
[Display(Name = "Last Name")]
public string ParentLastName { get; set; }
[Display(Name = "Email Address")]
public string ParentEmailAddress { get; set; }
[Display(Name = "Postal Address")]
public string ParentPostalNumber { get; set; }
[Display(Name = "Suburb")]
public string ParentSuburb { get; set; }
[Display(Name = "City")]
public string ParentCity {get; set;}
[Display(Name = "Post Code")]
public string ParentPostalCode {get; set;}
}
}
I think the problem lies here:
<a href='#Url.Action("SendApplication", "Home")'><input type="submit" value="Submit" /></a>
This won't work. Remove the tags entirely so only the input tag remains. Then assign the action and controllername to the form like this:
#Html.BeginForm("SendApplication", "Home", FormMethod.Post)

Categories