MVC3 validation problems - c#

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>
//....

Related

C# asp.net issue on Form with file type and text

I'm going straight to the point here guys,
I have a form. when I save the form... it only gets the firstname, middlename and lastname.. it doesn't get the files... however, if I only get the photo and comment out other inputs... the photo is captured on my model.. I dunno why it behaves like this.. I'm really new to asp.net mvc.. so please bear with me..
#model Impulse.ViewModels.AgentViewModel
#{
ViewBag.Title = "AgentForm";
Layout = "~/Views/Shared/_SiteLayout.cshtml";
}
<div class="custom-container">
<h1 class="title"><strong>Add New Agent</strong></h1>
<hr />
#using (Html.BeginForm("Save", "Agent", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<div class="col-md-3">
<div id="preview">
<img src="~/Content/Assets/no-image.png" id="profile_image" class="img-thumbnail" />
</div>
<div class="form-group">
<label>Profile Picture</label>
<input type="file" name="photo" id="photo" />
</div>
</div>
<div class="col-md-9">
<div class="row">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.Agent.FirstName)
#Html.TextBoxFor(m => m.Agent.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Agent.FirstName)
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.Agent.MiddleName)
#Html.TextBoxFor(m => m.Agent.MiddleName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Agent.MiddleName)
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.Agent.LastName)
#Html.TextBoxFor(m => m.Agent.LastName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Agent.LastName)
</div>
</div>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Save" />
}
</div>
Controller
[HttpPost]
public ActionResult Save(AgentModel agent)
{
//I debug here to see the data passed by my view
return Content("Sample");
}
Model
public class AgentModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
[FileSize(10240)]
[FileTypes("jpg,jpeg,png")]
public HttpPostedFileBase photo { get; set; }
}
you can try like this
Model
public class UploadFileModel
{
public UploadFileModel()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
View
#using (Html.BeginForm("UploadData", "Home", FormMethod.Post, new { encType="multipart/form-data" }))
{
#Html.TextBoxFor(m => m.FirstName)
<br /><br />
#Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br /><br />
<input type="submit" value="submit" name="submit" id="submit" />
}
Controller
public ActionResult UploadData(UploadFileModel model)
{
var file = model.Files[0];
return View(model);
}
you are binding to view to AgentViewModel so you will get AgentViewModel when you post server. so the parameter to action save should be viewmodel. Or Else change view to bind to AgentModel.
The file control that you have used is html input type. try using below code.
#Html.TextBoxFor(m => Model.File, new { type = "file" , accept=".pdf"})
#Html.ValidationMessageFor(m => Model.File)

ERROR uploading a image file in MVC? (No answers found)

In my MVC web app I'm attempting to upload a file while submitting a new record to the database but whenever that happens I receive "Object reference not set to an instance on an object" error. Below is my Model:
public class MenteeViewModel
{
public mentee mentee { get; set; }
public guardian guardian { get; set; }
public address address { get; set; }
public email email { get; set; }
public user users { get; set; }
public phnumber phnumber { get; set; }
public econtact econtact { get; set; }
[Display(Name = "School System")]
public int SelectedSSystemId { get; set; }
public IEnumerable<SelectListItem> SSystemItems { get; set; }
[Display(Name = "School")]
public int SelectedSchoolId { get; set; }
public IEnumerable<SelectListItem> SchoolItems { get; set; }
public ssystem ssystems { get; set; }
public school schools{ get; set; }
//This is for UPLOADING image and inserting image information to database
public HttpPostedFileBase File { get; set; }
public image image { get; set; }
}
Below is the section of code from the controller where I actually attempt to upload the file:
[HttpPost]
public ActionResult Create(MenteeViewModel menteeViewModel, HttpPostedFileBase file )
{
if (ModelState.IsValid)
{
var regModel = new RegisterModel();
try
{
DateTime now = DateTime.Now;
menteeViewModel.address.CreatedOn = now;
menteeViewModel.guardian.CreatedOn = now;
menteeViewModel.econtact.CreatedOn = now;
menteeViewModel.email.CreatedOn = now;
menteeViewModel.phnumber.CreatedOn = now;
menteeViewModel.mentee.addresses.Add(menteeViewModel.address);
menteeViewModel.mentee.guardians.Add(menteeViewModel.guardian);
menteeViewModel.mentee.econtacts.Add(menteeViewModel.econtact);
menteeViewModel.mentee.emails.Add(menteeViewModel.email);
menteeViewModel.mentee.phnumbers.Add(menteeViewModel.phnumber);
Regex pattern = new Regex("[-/]");
var strDob = (DateTime) menteeViewModel.mentee.dob;
var newDate = strDob.ToShortDateString();
newDate = pattern.Replace(newDate, "");
regModel.UserName = menteeViewModel.email.email_address;
regModel.Password = newDate;
WebSecurity.CreateUserAndAccount(regModel.UserName, regModel.Password);
Roles.AddUsersToRole(new[] {regModel.UserName}, "User");
menteeViewModel.mentee.active_flag = "N";
menteeViewModel.mentee.flag3 = menteeViewModel.schools.school_id.ToString();
menteeViewModel.mentee.CreatedOn = now;
var vfileName = Guid.NewGuid().ToString() + Path.GetFileName(menteeViewModel.image.image_path);
var path = Path.Combine(Server.MapPath("~/App_Data"), vfileName);
menteeViewModel.File.SaveAs(path);
menteeViewModel.image.image_path = path;
menteeViewModel.mentee.images.Add(menteeViewModel.image);
db.mentees.Add(menteeViewModel.mentee);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine(" - Property: \"{0}\", Error: \"{1}",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return RedirectToAction("Index");
}
return Create();
}
Below is the View:
BEMentoring.ViewModels.MenteeViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>MenteeViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.first_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.middle_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.middle_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.last_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.last_name)
</div>
<!-- Gender, DOB, Class Grade !-->
<div class="editor-label">
#Html.LabelFor(model => model.mentee.gender)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.gender)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.dob)
</div>
<div class="editor-field">
#Html.JQueryUI().DatepickerFor(model => model.mentee.dob).ChangeYear(new YearDefinition(-20, RelativeTo.SelectedYear), new YearDefinition(2012)).DateFormat("yyyy-mm-dd")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.class_grade)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.class_grade)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address.address1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.address.address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address.city)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.address.city)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address.state)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.address.state)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ssystems.ssystem_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ssystems.ssystem_id, new SelectList(ViewBag.SSystems as System.Collections.IEnumerable, "ssystem_id","ssystem_name"),
"--Select One--", new {id = "ddlSystem"})
</div>
<div class="editor-label">
#Html.LabelFor(model => model.schools.school_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.schools.school_id, new SelectList(ViewBag.Schools as System.Collections.IEnumerable, "school_id","school_name"),
"--Select One--", new {id = "ddlSchool"})
</div>
<div class="editor-label">
#Html.LabelFor(mode => Model.econtact.first_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.econtact.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(mode => Model.econtact.last_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.econtact.last_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.econtact.phone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.econtact.phone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.email.email_address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.email.email_address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.phnumber.area_code)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.phnumber.area_code)
#Html.EditorFor(model => model.phnumber.phone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.guardian.first_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.guardian.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.guardian.middle_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.guardian.middle_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.guardian.last_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.guardian.last_name)
</div>
<div>
#Html.LabelFor(model => model.File)
#Html.TextBoxFor(model => model.image.image_path, new {type = "file"})
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
I've searched but haven't been able to find a useful answer to this issue. If there is one that could help me, that I've missed please HELP! Thanks in advance
You are doing this:
<div>
#Html.LabelFor(model => model.File)
#Html.TextBoxFor(model => model.image.image_path, new {type = "file"})
</div>
Chenge it to:
<div>
#Html.LabelFor(model => model.File)
<input name="file" type="file">
</div>
This should map to your viewmodel File property. BTW, the name is not the best... but it should work.
In your controller, you are receiving the posted file as a parameter... not in the model itself... so you need to go get it from that parameter.
Use the HttpPostedFileBase file parameter to work with the file. I see a general lack of boundary checking in the code you posted. Be sure to check for null where objects could be null as in this case.

Exception Model.Questions null in mvc 3 view

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.

#Html.EditorFor (Image)

I am trying to allow a user to upload an image to our website and I'm not quite sure about how to use this. I have tried to use multiple types to define the image, including System.Drawing.Image and HttpPostedFileWrapper but the #Html.EditorFor always (understandably) brings up its attributes as fields to edit.
In my view I did have, instead of #Html.EditorFor I did have <input type="file" name="imageToUpload" /> but it didn't get taken through to my view as part of the Model? I am quite new to MVC so I am hoping it is something trivial.
Here is my View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>New Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
<input type="file" name="imageToUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
My Controller:
[HttpPost]
public ActionResult CreateImage(string brand, string collection, ImageEditViewModel imageEditViewModel)
{
string fileName = Guid.NewGuid().ToString();
string serverPath = Server.MapPath("~");
string imagesPath = serverPath + String.Format("Content\\{0}\\Images\\", Helper.Helper.ResolveBrand());
string newLocation = Helper.Helper.SaveImage(fileName, imagesPath, imageEditViewModel.Image.InputStream)
Image image = new Image
{
Collection = ds.Single<Collection>(c => c.Season == collection
&& c.Brand.Name == brand),
Description = imageEditViewModel.Description,
Location = "newLocation",
Order = Helper.Helper.GetImageOrder(brand, collection)
};
ds.InsertOnSubmit<Image>(image);
ds.SubmitChanges();
return RedirectToAction("Brand");
}
And finally the ViewModel:
public class ImageEditViewModel
{
public int CollectionId { get; set; }
public string Description { get; set; }
public HttpPostedFileWrapper Image { get; set; }
public int Order { get; set; }
}
Ensure to specify the correct enctype="multipart/form-data" on your form or you won't be able to upload files:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ImageToUpload)
</div>
<div class="editor-field">
<input type="file" name="imageToUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And if you wanted to use an EditorFor helper to generate the file input you could use the following:
<div class="editor-label">
#Html.LabelFor(model => model.ImageToUpload)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ImageToUpload)
</div>
and then define a custom editor template for the HttpPostedFileBase type (see below that you need to modify your model to use this type actually). So the editor template in ~/Views/Shared/EditorTemplates/HttpPostedFileBase.cshtml:
#model HttpPostedFileBase
#Html.TextBox("", null, new { type = "file" })
and on your view model use the HttpPostedFileBase type and make sure that the name of the property matches the name of the file input on your form:
public class ImageEditViewModel
{
public int CollectionId { get; set; }
public string Description { get; set; }
public HttpPostedFileBase ImageToUpload { get; set; }
public int Order { get; set; }
}
Also make sure to checkout the following blog post.

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