Why does this not display the display name? - c#

I'm trying to display the displaynames for the properties in my html in my ASP.NET MVC 4 application.
However even though I've set the displaynames in the viewmodel the raw variable names still gets displayed instead.
The viewmodel:
public class Manage_ManagePasswordViewModel
{
[Display(Name="Name")]
public string name;
[Display(Name = "SubID")]
public string subId;
[Display(Name = "Conversions")]
public int conversions;
[Display(Name = "Password")]
public string password;
public UserProfile owner;
public Manage_ManagePasswordViewModel(ProtectedPassword pw)
{
name = pw.Name;
subId = pw.SubId;
conversions = pw.GetConversions();
password = pw.Password;
owner = pw.Owner;
}
}
The cshtml file:
#model Areas.Admin.Models.ViewModels.Manage_ManagePasswordViewModel
<div class="editor-label">
#Html.DisplayNameFor(m => m.name):
#Html.DisplayTextFor(m => m.name)
</div>
<div class="editor-label">
#Html.DisplayNameFor(m => m.password):
#Html.DisplayTextFor(m => m.password)
</div>
<div class="editor-label">
#Html.DisplayNameFor(m => m.subId):
#Html.DisplayTextFor(m => m.subId)
</div>
<div class="editor-label">
#Html.DisplayNameFor(m => m.conversions):
#Html.DisplayTextFor(m => m.conversions)
</div>
<div class="editor-label">
#Html.DisplayNameFor(m => m.owner.UserName):
#Html.UserLink(Model.owner.UserName, Model.owner.UserId)
</div>

Use properties instead of fields, for ex.
[Display(Name="Name")]
public string name {get;set;}

Related

'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!!
:)

Model Validation With MVC Razor

I'm implementing MVC based website using the Razor engine.
I have created the validation to be in the model.
i.e. Student validation is like this:
[MetadataType(typeof(Student.StudentMetaData))]
public partial class Student
{
internal sealed class StudentMetaData
{
[Required(ErrorMessageResourceName = "FirstNameRequired", ErrorMessageResourceType = typeof(StudentMessages))]
public object FirstName { set; get; }
[Required(ErrorMessageResourceName = "FatherNameRequired", ErrorMessageResourceType = typeof(StudentMessages))]
public object FatherName { set; get; }
}
}
The student already implements the IDataErrorInfo interface. The data fields exist in the other partial class (the partial class created by T4 file).
The problem is when I use it with client validation in Razor view using:
#Html.TextBoxFor(m => m.FatherName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FatherName)
it doesn't get the messages I specified in my resource files.
I have tried the same technique before with WPF and it works just fine.
I allowed the client validation in the Web.config and used this in my view:
#{
HtmlHelper.ClientValidationEnabled = true;
}
Add Name space in modal class in mvc.
using System.ComponentModel.DataAnnotations;
public class TelePhones
{
[Required (ErrorMessage = "MobileNo is required")]
public long MobileNo { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
[DataType(DataType.Date)]
public string DateOfBirth { get; set; }
[Range(15, 70, ErrorMessage = "Price must be between 15 and 70")]
public int Age { get; set; }
}
client side validation in mvc
<div class="editor-label">
#Html.LabelFor(model => model.MobileNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MobileNo)
#Html.ValidationMessageFor(model => model.MobileNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DateOfBirth)
#Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Age)
#Html.ValidationMessageFor(model => model.Age)
</div>

Model' conflicts with the declaration Model on Grid.MVC (ASP.NET)

I have a form and using Grid.MVC to display in same page. When I try run my program, it show error : 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'..
Here the sample of my code
This is my model
public class Course
{
[DisplayName("Customer Name")]
public string customer { get; set; }
[DisplayName("Contact")]
public string contact { get; set; }
[UIHint("DropDownList")]
[Required(ErrorMessage = "Please select the package")]
public int CoursePackageID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required(ErrorMessage = "The date is required")]
[DisplayName("Date Of Register")]
public DateTime dtRegister { get; set; }
[DisplayName("Payment")]
public string payment { get; set; }
public List<CourseObject> lCourse { get; set; }
public class CourseObject
{
public int courseId { get; set; }
[DisplayName("Package")]
public string package { get; set; }
[DisplayName("Date Of Register")]
public DateTime date_register { get; set; }
[DisplayName("Payment")]
public string payment { get; set; }
}
}
And this is my CSHTML (Razor)
#model BangiProject.Models.Course
#using GridMvc.Html
#{
ViewBag.Title = "Register";
}
<h2>
Register</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
<div class="control-label">
#Html.LabelFor(model => model.customer)
</div>
<div class="form-control-static">
#Html.DisplayFor(model => model.customer)
</div>
<div class="control-label">
#Html.LabelFor(model => model.contact)
</div>
<div class="form-control-static">
#Html.DisplayFor(model => model.contact)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.CoursePackageID, new SelectList(ViewBag.CoursePackage as System.Collections.IEnumerable, "id", "course_name", new { #style = "drop-down" }),
"-Choose Package-", new { id = "cat" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.dtRegister)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.dtRegister)
#Html.ValidationMessageFor(model => model.dtRegister)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.payment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.payment)
#Html.ValidationMessageFor(model => model.payment)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div class="row">
#Html.Grid(Model.lCourse).Columns(columns =>
{
columns.Add(c => c.courseId).Titled("ID")
.Sanitized(false)
.Encoded(false)
.RenderValueAs(o => Html.ActionLink("Edit", "Edit", "Merchant", new { id = o.courseId }, null).ToHtmlString());
columns.Add(c => c.package).Titled("Package").Filterable(true);
columns.Add(c => c.date_register).Titled("Date Of Register").Filterable(true);
}).WithPaging(25).Sortable(true)
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The error show on this line
#Html.Grid(Model.lCourse).Columns
Please advice...
Usually this means that you're using the reserved "Model" keyword erroneously somewhere. In your case:
#Html.DropDownListFor(Model => Model.CoursePackageID...
Change this to:
#Html.DropDownListFor(model => model.CoursePackageID...
Try changing the line in question as below(lowercase 'm')...
#Html.Grid(model.lCourse).Columns

Fill in form based on dropdown selection (MVC 4)

I am using asp.net mvc 4
Is there a way to update the form based on selection made by the user?
(in this case I want to fill in address fields if something is picked from the dropdown list, otherwise a new address would need to be typed in)
My model:
public class NewCompanyModel
{
[Required]
public string CompanyName { get; set; }
public bool IsSameDayRequired { get; set; }
public int AddressID { get; set; }
public Address RegisterOfficeAddress { get; set; }
}
View:
#model ViewModels.NewCompanyModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { name = "frm", id = "frm" }))
{
#Html.ValidationSummary(true)
<fieldset id="test">
<legend>Company</legend>
<h2>Register office address</h2>
<div class="editor-label">
#Html.LabelFor(model => model.AddressID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.AddressID, (IList<SelectListItem>)ViewBag.Addresses, new {id = "address", onchange = "window.location.href='/wizard/Address?value=' + this.value;" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
#Html.ValidationMessageFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RegisterOfficeAddress.StreetName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RegisterOfficeAddress.StreetName)
#Html.ValidationMessageFor(model => model.RegisterOfficeAddress.StreetName)
</div>
and controller:
public ActionResult Address(string value)
{
//get the address from db and somehow update the view
}
The question is how do you update the 'model.RegisterOfficeAddress.StreetName' etc
Just to make clear this is just part of the form so I cannot submit it just yet.
Many thanks
Thanks for your help; I have decided to take a different approach:
On dropdown change I submit the form:
<div class="editor-label">
#Html.LabelFor(model => model.ServiceAddress.AddressID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ServiceAddress.AddressID, (IEnumerable<SelectListItem>)ViewBag.Addresses, new { onchange = "this.form.submit();" })
#Html.ValidationMessageFor(model => model.ServiceAddress.AddressID)
</div>
and then in controller:
[HttpPost]
public ActionResult NewDirector(NewDirectorVM vm, string value)
{
ModelState.Clear();
if (vm.ServiceAddress.AddressID > 0)
{
//Updates the properties of the viewModel
vm.ServiceAddress = _Repository.GetAddress(vm.ServiceAddress.AddressID);
}
return View("NewDirector", vm);
}
Please notice ModelState.Clear(); which actually allows the view to be updated from the controller (otherwise all the changes made the the viewModel by the controller would have been overwritten by the values in the view).
Common way in such cases is to update other fields via javascript:
$('##Html.IdFor(model => model.AddressID)').on('change',function(){
$.get(...,function(data){
$('##Html.IdFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)').val(data)
})
})

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