MVC3 Contact Form not Sending Email After POSTing - asp.net-mvc-3

I built a simple contact form that works great locally in my test 'mvc1application'. When I transfer the exact code to one of my sites where this form will be I get issues and am really stumped.
Scenario is when a user hits the site it checks to see if they are authenticated already (through an SSO system). If so a cookie is set and they are logged in. If you try to go to the site without logging in you currently get redirected to a 'AccessDenied.cshtml' view. That's no problem at all.
I have since replaced that View with a form (simple contact form) that the user can fill out to email the web master. I get the form to display properly, and on POST it gets a 200 and via Chrome dev tools I see the form content is POSTED. What is not happening is that I don't think my EmailViewModel.cs is being called and processing the form data. So no email is ever sent.
I'm really stumped and here is some of the sample code:
(My AccountController with some parts snipped out...)
[AllowAnonymous]
public ActionResult LogOn(string strEmail, string token)
{
DepartmentUser departmentuser = db.DepartmentUsers.SingleOrDefault(r => r.UserEmail == strEmail && r.Token == token);
if (departmentuser != null)
{
//verify that the token date + 1 day >= current datetime
if (departmentuser.TokenDate.Value.AddDays(1) >= DateTime.Now)
{
//if yes, then update to set token = null and datetime = null
departmentuser.Token = null;
departmentuser.TokenDate = null;
db.SaveChanges();
string userData = departmentuser.DepartmentUserID.ToString() + ":" + departmentuser.DepartmentID.ToString() + ":" + departmentuser.UserName;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, departmentuser.UserEmail,
DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false, userData);
string hashedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
Response.AppendCookie(cookie);
return Redirect("~/Home");
}
else
{
return View("RequestForm");
}
}
else
{
return View("RequestForm");
}
}
public ActionResult RequestForm(EmailViewModel emailVM)
{
if (!ModelState.IsValid)
{
return View(emailVM);
}
var email = new EmailViewModel
{
Name = emailVM.Name,
EmailAddress = emailVM.EmailAddress,
InternalTeamName = emailVM.InternalTeamName,
InternalTeamLeadName = emailVM.InternalTeamLeadName,
InternalDistEmail = emailVM.InternalDistEmail,
AverageNumCommsWeekly = emailVM.AverageNumCommsWeekly,
AverageNumPeopleSentWeekly = emailVM.AverageNumPeopleSentWeekly
};
string body = "Name: " + email.Name + "\n"
+ "Email: " + email.EmailAddress + "\n"
+ "Internal Team: " + email.InternalTeamName + "\n"
+ "Internal Team Lead: " + email.InternalTeamLeadName + "\n"
+ "Internal Team Lead Email: " + email.InternalTeamLeadEmail + "\n"
+ "Internal Distribution Email: " + email.InternalDistEmail + "\n"
+ "Average # of Communications Per Week: " + email.AverageNumCommsWeekly + "\n"
+ "Average # of People Emailed Per Week: " + email.AverageNumPeopleSentWeekly;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email.EmailAddress);
// for production put email in web.config for easy change
mail.To.Add("user#email.me");
mail.Subject = "Access Request";
mail.Body = body;
mail.IsBodyHtml = true;
// smtp is local directory in web.config for testing ATM...
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
mail.Dispose();
return View("RequestForm");
}
And my EmailViewModel.cs...
namespace MVC.Models
{
public class EmailViewModel
{
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
[Required]
public string InternalTeamName { get; set; }
[Required]
public string InternalTeamLeadName { get; set; }
[Required]
public string InternalTeamLeadEmail { get; set; }
[Required]
public string InternalDistEmail { get; set; }
[Required]
public string AverageNumCommsWeekly { get; set; }
[Required]
public string AverageNumPeopleSentWeekly { get; set; }
}
}
And lastly my Requestform.cshtml view...
#model CorpNewsMgr.Models.EmailViewModel
#{
ViewBag.Title = "Request Access";
Layout = "~/Views/Shared/_WideLayoutDenied.cshtml";
}
<p>
Currently you do not have the required credentials to access the site.
<br />
To request more information, or to request permission to access this system, please
contact:
</p>
<br />
<br />
<div>
<h3>
Please fill this form out to request access to the tool.</h3>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Request Access</legend>
<div class="editor-label">
#Html.LabelFor(Model => Model.Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.Name)
#Html.ValidationMessageFor(Model => Model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.EmailAddress)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.EmailAddress)
#Html.ValidationMessageFor(Model => Model.EmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.InternalTeamName)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.InternalTeamName)
#Html.ValidationMessageFor(Model => Model.InternalTeamName)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.InternalTeamLeadName)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.InternalTeamLeadName)
#Html.ValidationMessageFor(Model => Model.InternalTeamLeadName)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.InternalTeamLeadEmail)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.InternalTeamLeadEmail)
#Html.ValidationMessageFor(Model => Model.InternalTeamLeadEmail)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.InternalDistEmail)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.InternalDistEmail)
#Html.ValidationMessageFor(Model => Model.InternalDistEmail)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.AverageNumCommsWeekly)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.AverageNumCommsWeekly)
#Html.ValidationMessageFor(Model => Model.AverageNumCommsWeekly)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.AverageNumPeopleSentWeekly)
</div>
<div class="editor-field">
#Html.TextBoxFor(Model => Model.AverageNumPeopleSentWeekly)
#Html.ValidationMessageFor(Model => Model.AverageNumPeopleSentWeekly)
</div>
<p>
<input type="submit" value="Send" />
</p>
</fieldset>
}
</div>
<br />
<p>
Thank you,<br />
</p>
SO when the page is loaded the form loads fine (yay). I can fill it out and validate it fine (yay). On Submit I get a 200 and POST looks fine (I can see the fields in the POST) but nothing happens. The page reloads as an empty form and I don't see any emails in my pickup folder or anything.
Again, on my local dev test site I can get it to work and route through ok. Here I cannot. I think the issue is with the top of the AccountController and how it's pulling the View but I'm stumped (and tired) from trying to figure this out.
Oh, and it's my 1st large foray into MVC form building from standard WebForms...
Any thoughts?
thanks!

I was going to comment, but it ran too long.
You need to post the action that the Requestform.cshtml posts to, also your account controller code is not really needed here. My guess is your hosting environment is shared hosting and there is something preventing your emailing code from functioning.
The first thing you may want to do is if your email code is inside a try catch, temporarily comment our the try catch so it will throw and error. This should at least help give you an idea of what is going on.
The next thing to do is try adding Elmah for mvc3, you can add this via Nuget in Visual Studios. Make sure to use the Elmah for MVC3 one since it will have everything mostly setup for you. This will allow you to see it there are any errors being thrown.
Otherwise without seeing your actual email code I can't be of more help.

Related

Asp.net mvc 3 model doesn't get automatically bind?

I'm studying asp.net mvc 3 right now and I'm following this tutorial Contoso University
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
I'm in this part where editing a model is handled with Optimistic Concurrency
I'm aware that by using something like
[HttpPost]
public ActionResult Edit(Department department)
the model will automatically be binded, even without a hidden field for the id of the department to be edited, and the edit will not fail.
But whenever I try to remove the two hiddenfields in the view of this one:
#model MvcContosoUniversity.Models.Department
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<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>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Department</legend>
#Html.HiddenFor(model => model.DepartmentID)
#Html.HiddenFor(model => model.Timestamp)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Budget)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Budget)
#Html.ValidationMessageFor(model => model.Budget)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.InstructorID, "Administrator")
</div>
<div class="editor-field">
#Html.DropDownList("InstructorID", String.Empty)
#Html.ValidationMessageFor(model => model.InstructorID)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I get an error in the controller, here's the code for the controller:
// GET: /Department/Edit/5
public ActionResult Edit(int id)
{
Department department = db.Departments.Find(id);
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
//
// POST: /Department/Edit/5
[HttpPost]
public ActionResult Edit(Department department)
{
try
{
if (ModelState.IsValid)
{
db.Entry(department).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
//Another option is to put the try-catch inside a function
try
{
var databaseValues = (Department)entry.GetDatabaseValues().ToObject();
var clientValues = (Department)entry.Entity;
if (databaseValues.Name != clientValues.Name)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.Name);
if (databaseValues.Budget != clientValues.Budget)
ModelState.AddModelError("Budget", "Current value: "
+ String.Format("{0:c}", databaseValues.Budget));
if (databaseValues.StartDate != clientValues.StartDate)
ModelState.AddModelError("StartDate", "Current value: "
+ String.Format("{0:d}", databaseValues.StartDate));
if (databaseValues.InstructorID != clientValues.InstructorID)
ModelState.AddModelError("InstructorID", "Current value: "
+ db.Instructors.Find(databaseValues.InstructorID).FullName);
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink.");
department.Timestamp = databaseValues.Timestamp;
}
catch(NullReferenceException e)
{
ModelState.AddModelError("","Error \n "+e.Message);
}
}
catch (DataException)
{
//Log the error (add a variable name after Exception)
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
Here is the code for the model:
public class Department
{
public int DepartmentID { get; set; }
[Required(ErrorMessage = "Department name is required.")]
[MaxLength(50)]
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:c}")]
[Required(ErrorMessage = "Budget is required.")]
[Column(TypeName = "money")]
public decimal? Budget { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Start date is required.")]
public DateTime StartDate { get; set; }
[Display(Name = "Administrator")]
public int? InstructorID { get; set; }
public virtual Instructor Administrator { get; set; }
public virtual ICollection<Course> Courses { get; set; }
[Timestamp]
public Byte[] Timestamp { get; set; }
}
Is it possible to make it work without using hiddenfields?
Sir/Ma'am your answers would be of great help. Thank you++
Based on your HttpPost action signature, no, this isn't possible. You're performing an Edit so it will need the Id of the row that is being updated. Since you're not mapping the Id in the action method signature, and the hidden fields holding that information aren't there, the id will never get mapped to the Department model. The result being that you would try to perform an update without a row id.
EDIT: You could modify your action signature like so: Edit(int id, Department department), but then you'd have to manually set the department.Id to the id passed and that would seem to make the model somewhat disjointed.

How to make Optimistic Concurrency editing in Asp.net mvc 3 without using hiddenfields in the view?

I'm studying asp.net mvc 3 right now and I'm following this tutorial Contoso University
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
I'm in this part where editing a model is handled with Optimistic Concurrency
I'm aware that by using something like
[HttpPost]
public ActionResult Edit(Department department)
the model will automatically be binded, even without a hidden field for the id of the department to be edited, and the edit will not fail.
But whenever I try to remove the two hiddenfields in the view of this one:
#model MvcContosoUniversity.Models.Department
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<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>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Department</legend>
#Html.HiddenFor(model => model.DepartmentID)
#Html.HiddenFor(model => model.Timestamp)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Budget)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Budget)
#Html.ValidationMessageFor(model => model.Budget)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.InstructorID, "Administrator")
</div>
<div class="editor-field">
#Html.DropDownList("InstructorID", String.Empty)
#Html.ValidationMessageFor(model => model.InstructorID)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I get an error in the controller, here's the code for the controller:
// GET: /Department/Edit/5
public ActionResult Edit(int id)
{
Department department = db.Departments.Find(id);
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
//
// POST: /Department/Edit/5
[HttpPost]
public ActionResult Edit(Department department)
{
try
{
if (ModelState.IsValid)
{
db.Entry(department).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
//Another option is to put the try-catch inside a function
try
{
var databaseValues = (Department)entry.GetDatabaseValues().ToObject();
var clientValues = (Department)entry.Entity;
if (databaseValues.Name != clientValues.Name)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.Name);
if (databaseValues.Budget != clientValues.Budget)
ModelState.AddModelError("Budget", "Current value: "
+ String.Format("{0:c}", databaseValues.Budget));
if (databaseValues.StartDate != clientValues.StartDate)
ModelState.AddModelError("StartDate", "Current value: "
+ String.Format("{0:d}", databaseValues.StartDate));
if (databaseValues.InstructorID != clientValues.InstructorID)
ModelState.AddModelError("InstructorID", "Current value: "
+ db.Instructors.Find(databaseValues.InstructorID).FullName);
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink.");
department.Timestamp = databaseValues.Timestamp;
}
catch(NullReferenceException e)
{
ModelState.AddModelError("","Error \n "+e.Message);
}
}
catch (DataException)
{
//Log the error (add a variable name after Exception)
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
Here is the code for the model:
public class Department
{
public int DepartmentID { get; set; }
[Required(ErrorMessage = "Department name is required.")]
[MaxLength(50)]
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:c}")]
[Required(ErrorMessage = "Budget is required.")]
[Column(TypeName = "money")]
public decimal? Budget { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Start date is required.")]
public DateTime StartDate { get; set; }
[Display(Name = "Administrator")]
public int? InstructorID { get; set; }
public virtual Instructor Administrator { get; set; }
public virtual ICollection<Course> Courses { get; set; }
[Timestamp]
public Byte[] Timestamp { get; set; }
}
Is it possible to make it work without using hiddenfields?
Sir/Ma'am your answers would be of great help. Thank you++
You need to have the id value coming from somewhere, or that entity can't be saved... how does EF know what ID it's saving without it?
It doesn't have to be via hidden field; It's probably there in the query string from the initial GET request for the edit action.

Can I restrict client-side validation to specific fields?

I have a Form where I successfully use unobtrusive-validation with the [remote] annotation.
I have other fields in the Form with [required] annotation in the model but I don't want client-side validation for these fields.
I only want server-side validation for [required] fields
I haven't found a solution and I wonder if it's easily feasible?
EDIT :
A part of my code
Part of my model :
I would like the first field : "Email" use Unobtrusive-validation and the second one : "PasswordHash" only use server-side validation even if it has [required] annotation.
Finally, i don't want an AJAX error message for all my form 's fields.
[Required(ErrorMessageResourceType = typeof(Project.Resources.Models.Accounts.User), ErrorMessageResourceName = "EMAIL_REQUIRED")]
[Display(Name = "EMAIL_DISPLAY", ResourceType = typeof(Project.Resources.Models.Accounts.User))]
[Remote("EmailExists", "User", "An account with this email address already exists.")]
public string Email { get; set; }
[Required(ErrorMessageResourceType = typeof(Project.Resources.Models.Accounts.User), ErrorMessageResourceName = "PASSWORDHASH_REQUIRED")]
[DataType(DataType.Password)]
[Display(Name = "PASSWORDHASH_DISPLAY", ResourceType = typeof(Project.Resources.Models.Accounts.User))]
public string PasswordHash { get; set; }
Part of the action in Controller
Server-side validation :
[HttpPost]
public ActionResult Register(User user)
{
if (ModelState.IsValid )
{
DataContext.User.Add(user);
DataContext.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Ajax validation :
public JsonResult EmailExists(string email)
{
User user = DataContext.User.SingleOrDefault(x => x.Email == email);
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(
string.Format("an account for address {0} already exists.",
email), JsonRequestBehavior.AllowGet);
}
Part of the view :
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PasswordHash)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PasswordHash)
#Html.ValidationMessageFor(model => model.PasswordHash)
</div>
<p>
<input type="submit" name="op" id="edit-submit" value="#Project.Resources.Views.User.Register.SUBMIT_FORM" class="form-submit art-button" />
</p>
}
When I click on the sumbit button i would like a server-side validation.
And for some specific fields like Email i would like an Ajax Validation.
there might be better ways, but one way to accomplish this is to do the following
#using (Html.BeginForm("Register", "Home", FormMethod.Post, new { id = "registerForm" }))
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PasswordHash)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PasswordHash)
#Html.ValidationMessageFor(model => model.PasswordHash)
</div>
<p>
<input type="submit" name="op" id="edit-submit" value="#Project.Resources.Views.User.Register.SUBMIT_FORM" class="form-submit art-button" />
</p>
}
<script type="text/javascript">
// add the rules for the fields that you want client-side validation on
// leave out the fields that you dont want client-side validation. they will be validated
// on server side.
$("#registerForm").validate({
rules: {
Email: { required: true }
},
messages: {
Email: { required : "Email is required" }
}
});
</script>

Telerik MVC 3 (Razor) Q1 2012 Editor EditorFor() Binding Returns Null Value and Unobtrusive Validation Doesn't Work

I'm currently working on my first MVC3 application at work (using the Razor view engine), and decided to use the open source Telerik Q1 2012 controls since they will provide a lot of the functionality I need (and look nice as well). Right now the issue I'm having is using the Telerik Editor control and binding to my view model. I have standard Html.EditorFor() controls on the page that return the value in the ViewModel correctly, but the property bound to Telerik Editor is null. Their documentation is completely useless (it only mentions EditorFor one time), and it doesn't seem like they answer too many questions on the forum either. My main question is, how do I bind the Telerik MVC3 Editor to a model and have it set the property that's bound to it? My code for the view model is below (thanks for any help you can provide, and keep in mind, I'm brand new to MVC, I'm doing this project on my own to get familiar with it and introduce some new technologies to the group):
public class SupportViewModel
{
[Display(Name = "Ticket Subject")]
[MaxLength(30)]
[Required(ErrorMessage = "The ticket subject is required.")]
public string TicketSubject { get; set; }
[Display(Name = "Support Issue")]
[Min(1, ErrorMessage = "You must select a support issue.")]
public int SupportIssueID { get; set; }
[Display(Name = "Ticket Priority")]
[Min(1, ErrorMessage = "You must select a ticket priority.")]
public int TicketPriorityID { get; set; }
//public string EmployeeID { get; set; }
public bool IsClosed { get; set; }
[Required(ErrorMessage = "The detail message is required.")]
public string DetailMessage { get; set; }
}
View Code:
#model RadixMVC.ViewModels.SupportViewModel
#{
ViewBag.Title = "Create New Support Ticket";
}
<h2>Radix Support: Create New Support Ticket</h2>
<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>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset style="width: 500px">
<legend>Create New Support Ticket</legend>
<div class="editor-label">
#Html.LabelFor(model => model.TicketSubject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TicketSubject)
#Html.ValidationMessageFor(model => model.TicketSubject)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SupportIssueID)
</div>
<div class="editor-field">
#Html.DropDownList("SupportIssueID", string.Empty)
#Html.ValidationMessageFor(model => model.SupportIssueID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TicketPriorityID)
</div>
<div class="editor-field">
#Html.DropDownList("TicketPriorityID", string.Empty)
#Html.ValidationMessageFor(model => model.TicketPriorityID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsClosed)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsClosed)
#Html.ValidationMessageFor(model => model.IsClosed)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DetailMessage)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.DetailMessage)*#
#Html.ValidationMessageFor(model => model.DetailMessage)
<br />
#{ Html.Telerik().EditorFor(model => model.DetailMessage)
.Name("DetailMessageEditor")
.HtmlAttributes(new { style = "height: 200px" })
.Encode(false)
.Render();
}
</div>
<div>
<br />
<input type="submit" value="Create Ticket" title="Submits a new support ticket" />
<input type="submit" onclick="parent.location='#Url.Action("Index", "Support", "Index")'" value="Cancel" title="Return to Support Home" />
</div>
</fieldset>
}
And finally, Controller Code:
[HttpPost]
public ActionResult Create(SupportViewModel vm)
{
if (ModelState.IsValid)
{
SupportTicket SupportTicket = new SupportTicket()
{
SupportTicketID = Guid.NewGuid(),
EmployeeID = "123456",
TicketOpenDate = DateTime.Now,
TicketModifiedDate = DateTime.Now,
IsClosed = vm.IsClosed,
TicketSubject = vm.TicketSubject,
SupportIssueID = vm.SupportIssueID,
TicketPriorityID = vm.TicketPriorityID
};
TicketDetail TicketDetail = new TicketDetail()
{
TicketDetailID = Guid.NewGuid(),
SupportTicketID = SupportTicket.SupportTicketID,
TicketOrder = 1,
EmployeeID = "123456",
DetailDate = DateTime.Now,
DetailMessage = vm.DetailMessage
};
SupportTicket.TicketDetails.Add(TicketDetail);
db.SupportTickets.Add(SupportTicket);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SupportIssueID = new SelectList(db.SupportIssues, "SupportIssueID", "Name", vm.SupportIssueID);
ViewBag.TicketPriorityID = new SelectList(db.TicketPriorities, "TicketPriorityID", "Name", vm.TicketPriorityID);
return View(vm);
}
I was able to get this working. The documentation is either very outdated or just doesn't explain how to do this very well (probably both). But I was able to get this working by making the following change to my Razor syntax:
<div class="editor-label">
#Html.LabelFor(model => model.DetailMessage)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.DetailMessage)*#
#Html.ValidationMessageFor(model => model.DetailMessage)
<br />
#{ Html.Telerik().EditorFor(model => model.DetailMessage)
//.Name("DetailMessageEditor")
.HtmlAttributes(new { style = "height: 200px" })
.Encode(true)
.Render();
}
</div>
Removing the "Name" property from the control solved the problem of not getting anything back, but when I tried to save, I immediately got an error (something to do with XSS, cross-site scripting), and I assumed it was because the HTML wasn't being encoded. I changed the Encode property to true, and now all is good.
Came across a similar thing today.
I was using a View Model and the property I wanted to bind to was was a property of a child object in the View Model.
When I submitted, the value in the RTE was not being bound. When I looked in Request.From object I could see the the value was being returned in the correct format for it to bound in the usual way so I was a little confused.
Anyway, if you want it to bind you need to give the exact name of your property to the the RTE so in your case
.Name("DetailMessage")
should work but
.Name("DetailMessageEditor")
will not.
Im my case i had to name the RTE
.Name("object.Property")
where object is the child object on the View model where my property lives to get it to work
Hope this helps someone.

jQuery UI Datepicker not Posting to Server after Deployment

So I published a ASP.Net MVC3 project that uses the jQuery UI datepickers on to a IIS server. The datepickers don't seem to post their values and revert to default values on the back end.
Locally, though it works like a charm. It's simple jQuery without any options on the datepicker.
Any clue as to why that would happen?
Let me know what I can post to help find a solution.
Thanks!
The model I am trying to post back:
public class Report
{
[Required]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime From { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime To { get; set; }
public virtual Car Car { get; set; }
public virtual IEnumerable<Review> Reviews { get; set; }
}
The form I am using:
#model Cars.Models.Report
<h3>Create a report</h3>
#using (Html.BeginForm("Generate", "Report"))
{
<div>
<div class="span-5">
<div class="editor-label">
#Html.LabelFor(model => model.From)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.From, new { #class = "datepicker lilbig" })
</div>
</div>
<div class="span-5 last">
<div class="editor-label">
#Html.LabelFor(model => model.To)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.To, new { #class = "datepicker lilbig" })
</div>
</div>
<div class="span-11 last">
<div class="prepend-5 last">
<input class="bigbtn" type="submit" value="Create" />
</div>
<div>
#Html.ValidationSummary(true)
#Html.ValidationMessageFor(model => model.From)
#Html.ValidationMessageFor(model => model.To)
</div>
</div>
</div>
}
Method I am posting to:
[HttpPost]
public ActionResult Generate(Report model)
{
try
{
MembershipUser currentUser = Membership.GetUser(HttpContext.User.Identity.Name);
Guid id = (Guid)currentUser.ProviderUserKey;
Car currentCar = CarRepository.Get(id);
currentCar.LastReportCreated = DateTime.Now;
currentCar = CarRepository.Update(currentCar, true);
model.Car = currentCar;
model.Reviews = model.Car.Reviews.Where(s => s.LoggedAt.Date >= model.From.Date &&
s.LoggedAt.Date <= model.To.Date);
return View("Report", model);
}
catch(Exception ex)
{
return View("Error");
}
}
The jQuery looks like this:
$(document).ready(function () {
$(".datepicker").datepicker();
});
Check that the datepicker version on the server is current and running bug-free. Also double check your form data before it gets posted - make sure the date fields have values:
$(document).ready(function () {
$("form").submit(function(){
$(".datepicker").each(function(){
alert( $(this).attr("name") +": "+ $(this).value() );
});
});
});

Resources