MVC 5 Using POSTAL with Models - model-view-controller

I am trying to use Postal in Mvc.5.2.3 and Razor.3.2.3 in Visual studio Ultimate 2013, I have many forms to generate for this project and would like to use Views as i would like to Post content to a database as well as send an email out with the information from the form using Postal. I am also creating partial Views for the header and footer so they are always the same and only the content of the email is changed by what forms are used. The email that will be sent will be to the sales department for review, a second email needs to be sent to the person that filled out the form saying thank you and showing the information they sent with the form. I hope this makes sense. I had the database working properly but had so much trouble getting the email system to work i have just started over and just trying to get the email system working properly.
My Model
using Postal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace APP.Models.Forms.Company
{
public class ContactEmail : Email
{
public ContactEmail() : base("Contact")
{ }
public int ContactId { get; set; }
public Guid TicketId { get; set; }
[Required(ErrorMessage = "Please Enter your First Name!")]
[StringLength(100, MinimumLength = 3)]
[DisplayName("First Name")]
[Display(Order = 1)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please Enter your Last Name!")]
[StringLength(100, MinimumLength = 3)]
[DisplayName("Last Name")]
[Display(Order = 2)]
public string LastName { get; set; }
[DisplayName("Business Name")]
[Display(Order = 3)]
public string BusinessName { get; set; }
[Required(ErrorMessage = "You have not entered a phone numer, Please enter your phone number so we can get back to you!")]
[DataType(DataType.PhoneNumber)]
[DisplayName("Phone Number")]
[RegularExpression(#"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$", ErrorMessage = "Please enter proper format of one of the following: (555)555-5555, 555-555-5555, 5555555555")]
[StringLength(32)]
[Display(Order = 4)]
public string Phone { get; set; }
[Required(ErrorMessage = "You have not entered an Email address, Please enter your email address!")]
[DataType(DataType.EmailAddress)]
[DisplayName("Email Address")]
[MaxLength(50)]
[RegularExpression(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "The Email field is not valid, Please enter a valid email address!")]
[Display(Order = 5)]
public string UserEmailAddress { get; set; }
[Required(ErrorMessage = "You have not entered a message, Please enter a message!")]
[DataType(DataType.MultilineText)]
[StringLength(2000)]
[DisplayName("Message")]
[Display(Order = 6)]
public string Message { get; set; }
public Source Source { get; set; }
public HttpPostedFileBase Upload { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return LastName + ", " + FirstName;
}
}
}
}
The Controler:
using APP.Models;
using APP.Models.Forms.Company;
using Postal;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace APP.Controllers
{
public class FormsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
#region Main Forms Page
// Forms Page Blank with unautherized access
public ActionResult Index()
{
return View();
}
#endregion
#region Contact_Form
// GET: Forms/Create
public ActionResult Contact()
{
return View();
}
// POST: Forms/Submit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Send(ContactEmail form)
{
var email = new Email("Contact")
{
To = "webmaster#somedomain.com",
MyModel = ContactEmail //Says its a "type" but used like a variable.
}
email.Send();
}
#endregion
#region Condo Form
#endregion
#region Personal Flood Form
#endregion
#region Home Insurance Form
#endregion
#region Renters Insurance Form
#endregion
#region WaterCraft Insurance Form
#endregion
#region Life Insurance Form
#endregion
#region Business Flood Form
#endregion
#region Business Risk Form
#endregion
#region Business Inland Marine Form
#endregion
#region Business Group Health Form
#endregion
#region Form
#endregion
#region Not Available Forms Page
// Forms Page Blank with unautherized access
public ActionResult Not_Available()
{
return View();
}
#endregion
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Form View:
#model APP.Models.Forms.Company.ContactEmail
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout_LandingPages.cshtml";
}
<div class="box">
<h2>Contact Form</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contact </h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
<div class="col-lg-6">
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
#Html.LabelFor(model => model.BusinessName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BusinessName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BusinessName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
#Html.LabelFor(model => model.UserEmailAddress, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.UserEmailAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserEmailAddress, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Message, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
</div>
</div></div>
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit Form" class="btn btn-default" /> 
<input type="reset" value="Reset Form" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Cancel", "Index", "Home")
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My email View is Contact.cshtml and is located in the email folder under Views.

You already have an email object, so just call send:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Send(ContactEmail form)
{
form.Send();
// You could also save this to the database here...
}

Related

Selected Dropdown value is not inserted into database but textbox value does

Here what I have tried to achieve is that a region has many zones so that zone is populated from a database then a user inserts the name of the region in the textbox then he selects different zones from the dropdown list the selected zone value should keep once selected and clicks the submit button. When the submit button has clicked the name of the region is inserted into the database but the selected dropdown list value is not inserted. here is the code that I have tried
the region controller
// GET: Regions
public ActionResult Index()
{
var regions = db.Regions.Include(r => r.Zone);
return View(regions.ToList());
}
// GET: Regions/Create
public ActionResult Create()
{
Regions zones = new Regions();
zones.regioness = PopulateZones();
ViewBag.ZoneID = new SelectList(db.Zones, "ZoneID", "ZoneName");
return View(zones);
}
public List<SelectListItem> PopulateZones()
{
List<SelectListItem> zones = new List<SelectListItem>();
string conString = ConfigurationManager.ConnectionStrings["StoreContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT ID, ZoneName FROM Zones", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new SelectListItem
{
Text = sdr["ZoneName"].ToString(),
Value = sdr["ID"].ToString()
});
}
}
con.Close();
}
}
return zones;
}
[HttpPost]
public ActionResult Create([Bind(Include = "ID,RegionName")] Regions reg)
{
reg.regioness = PopulateZones();
foreach (SelectListItem item in reg.regioness)
{
if (item.Value == reg.ID.ToString())
{
item.Selected = true;
db.Regions.Add(reg);
db.SaveChanges();
break;
}
}
return View(reg);
}
And my Region model is
public class Regions
{
public int ID { get; set; }
public string RegionName { get; set; }
[NotMapped]
public List<SelectListItem> regioness { get; set; }
public int? ZoneID { get; set; }
public virtual Zones Zone { get; set; }
}
and Zone model class
public class Zones
{
[Key]
public int ID { get; set; }
public string ZoneName { get; set; }
public virtual ICollection<Regions> Regions { get; set; }
}
and my create view in region
#model RegionAndZones.Models.Regions
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Regions</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RegionName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RegionName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RegionName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ZoneID, "ZoneID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("ZoneID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.ValidationMessageFor(model => model.ZoneID, "", new { #class = "text-danger" })
#Html.DropDownListFor(m => m.ID, new SelectList(Model.regioness, "Value", "Text"), "Please select")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
is there any one who can help me any help would be appreciated

ModelState.AddModelError for Ajax loaded partials

I have a partial view on my main page that loads a form, the model is below:
public class CreateRequestViewModel
{
[Required]
public short ClientId { get; set; }
[Required]
public Guid SystemId { get; set; }
[Required]
public string RequestedUsername { get; set; }
public string TicketReference { get; set; }
public string Notes { get; set; }
public List<SelectListItem> Clients { get; set; }
public List<SelectListItem> Systems { get; set; }
}
This is the partial view:
#model Models.CreateRequestViewModel
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-12">
<h1>Create a Request</h1>
</div>
<div class="col-lg-8 col-md-8 col-sm-12 right">
<div class="form-group">
#Html.DropDownListFor(m => m.ClientId, Model.Clients, htmlAttributes: new { #class = "form-control form-control-lg", #id = "ClientSelect" })
#Html.ValidationMessageFor(m => m.ClientId, "", htmlAttributes: new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.DropDownListFor(m => m.SystemId, Model.Systems, htmlAttributes: new { #class = "form-control form-control-lg", #id = "ClientSystemSelect" })
#Html.ValidationMessageFor(m => m.SystemId, "", htmlAttributes: new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.RequestedUsername, htmlAttributes: new { #class = "form-control form-control-lg", #placeholder = "Username" })
#Html.ValidationMessageFor(m => m.RequestedUsername, "", htmlAttributes: new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.TicketReference, htmlAttributes: new { #class = "form-control form-control-lg", #placeholder = "Ticket reference" })
</div>
<div class="form-group">
#Html.TextAreaFor(m => m.Notes, htmlAttributes: new { #class = "form-control form-control-lg", #rows = 3, #placeholder = "Notes..." })
</div>
<input type="Submit" class="btn btn-secondary btn-block send-request" value="Submit" name="">
</div>
</div>
This is how I'm loading the page:
<div class="container">
<div class="row">
<div class="col-lg-6">
<form asp-action="CreateRequest" asp-controller="Access"
data-ajax="true"
data-ajax-method="POST"
data-ajax-mode="replace"
data-ajax-update="#createRequest">
<div id="createRequest">
#await Html.PartialAsync("_CreateRequest", Model.CreateRequestModel)
</div>
</form>
</div>
</div>
</div>
With the model as it is and using the unobtrusive javascript, leaving the RequestedUsername blank for example will result in the form not being submitted and a validation message appearing for it. This is great.
However, I have a requirement to check the form data against entries in a database first and throw an error if there's an existing record. I thought that, with all the client side validation passing, I'd use ModelState.AddModelError in the controller like so:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateRequest(CreateRequestViewModel model)
{
if(model.RequestedUsername == "someincorrectvalue"){ //actual logic removed for brevity
ModelState.AddModelError("RequestedUsername", "Already in use");
}
if(!ModelState.IsValid)
{
//reset lists on model, removed
return PartialView("_CreateRequest", model);
}
_logger.LogInformation("CreateRequest successful");
return RedirectToAction(nameof(Index));
}
However, if I use ModelState.AddModelError, the return PartialView("_CreateRequest", model) call ends up reloading the whole page as if it's returning a full View.
I'm at a loss as to why this is happening. The difference I can see is that i'm adding a ModelState error inside the controller, whereas validation is happening client side otherwise.
Anyone have an idea?
So, this turned out to be a combination of problems. To begin with, the unobtrusive Ajax scripts I had within my solution were not performing. I don't know why but I replaced them with one from the CDN: https://ajax.aspnetcdn.com/ajax/jquery.unobtrusive-ajax/3.2.5/jquery.unobtrusive-ajax.min.js
That solved the problem of the whole page reloading instead of the partial being returned via unobtrusive ajax.
The second problem was that, on success, I was redirecting to the Index controller action instead of returning a Partial again. This was causing the entire Index page to be rendered inside the div i'd chosen as my ajax target. My controller action now looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateRequest(CreateRequestViewModel model)
{
if(model.RequestedUsername == "someincorrectvalue"){ //actual logic removed for brevity
ModelState.AddModelError("RequestedUsername", "Already in use");
}
if(!ModelState.IsValid)
{
//reset lists on model, removed
return PartialView("_CreateRequest", model);
}
_logger.LogInformation("CreateRequest successful");
// reset lists on model, removed
ModelState.Clear(); // get rid ofany model details to make way for a new request
return PartialView("_CreateRequest", model);
}

I am trying to upload an image using ASP.NET Core 3.0 MVC

I am trying to upload and save an image using ASP.NET Core 3.0 MVC and am having some issues. I can get the image to upload but it will not save to the database. I have been looking at other examples but am struggling with getting it to do what I want it to do. I am still new to programming in ASP.NET Core 3.0 MVC, so I might be just over looking something.
I am hopping someone out there with a much bigger brain then mine can help me out and show me where I have gone wrong.
Thanks in advance for any help.
Controller: EmployeeControler:
[HttpPost]
[ValidateAntiForgeryToken]
public async System.Threading.Tasks.Task<IActionResult> CreateAsync([Bind] Employee employee, IFormFile EmployeeImage)
{
if (ModelState.IsValid)
{
objemployee.AddEmployee(employee);
}
if (EmployeeImage != null && EmployeeImage.Length > 0)
{
var fileName = Path.GetFileName(EmployeeImage.FileName);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), #"wwwroot\Images", fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await EmployeeImage.CopyToAsync(fileStream);
return RedirectToAction("Index");
}
}
return View(employee);
}
Model: EmployeeDataAccessLayer:
// To add new employee record
public void AddEmployee(Employee employee)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SP_Add_Worker", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmployeeNumber", employee.EmployeeNumber);
cmd.Parameters.AddWithValue("#PositionTitle", employee.PositionTitle);
cmd.Parameters.AddWithValue("#FirstName", employee.FirstName);
cmd.Parameters.AddWithValue("#LastName", employee.LastName);
cmd.Parameters.AddWithValue("#Dept", employee.Dept);
cmd.Parameters.AddWithValue("#HireDate", employee.HireDate);
cmd.Parameters.AddWithValue("#EmployeeImage", employee.EmployeeImage);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Model Employee:
public class Employee
{
[Key]
public int ID { get; set; }
[Required(ErrorMessage = "Clock Number is required")]
public string EmployeeNumber { get; set; }
[Required(ErrorMessage = "Position Title is required")]
public string PositionTitle { get; set; }
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Department is required")]
public string Dept { get; set; }
[Required(ErrorMessage = "Hire Date is required")]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HireDate { get; set; }
[Required(ErrorMessage = "Please choose file to upload.")]
public string EmployeeImage { get; set; }
}
View Create:
#model Flexfab.Models.Employee
#{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Employees</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Clock Number:</label>
#Html.TextBoxFor(model => model.EmployeeNumber, new { #class = "form-control", #placeholder = "Clock Number" })
<span asp-validation-for="EmployeeNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label>Position:</label>
#Html.TextBoxFor(model => model.PositionTitle, new { #class = "form-control", #placeholder = "Position Title" })
<span asp-validation-for="PositionTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label>First Name</label>
#Html.TextBoxFor(model => model.FirstName, new { #class = "form-control", #placeholder = "First Name" })
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label>Last Name:</label>
#Html.TextBoxFor(model => model.LastName, new { #class = "form-control", #placeholder = "Last Name" })
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label>Dept:</label>
#Html.TextBoxFor(model => model.Dept, new { #class = "form-control", #placeholder = "Dept" })
<span asp-validation-for="Dept" class="text-danger"></span>
</div>
<div class="form-group">
<label>Hire Date:</label>
#Html.TextBoxFor(model => model.HireDate, new { #class = "form-control", #placeholder = "mm/dd/yyyy" })
<span asp-validation-for="HireDate" class="text-danger"></span>
</div>
<div class="form-group">
<label>Employee Picture:</label>
<br />
<input type="file" id="EmployeeImage" name="EmployeeImage">
#Html.HiddenFor(model => model.EmployeeImage, new { #class = "form-control" })
<span asp-validation-for="EmployeeImage" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
You cannot save images or other types of files in database, but instead you will be able the save only the path of the file. The image would be saved in the folder wwwroot\Images. To retrieve the file you need first to save that file.
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await EmployeeImage.CopyToAsync(fileStream);
employee.EmloyeeImage = fileName.Uri.OriginalString;
return RedirectToAction("Index");
}

html.dropdownlist MVC3 confusion

This works for me but how do I do the same thing using html.dropdownlist?
Notice that the value passed is not the value that is shown to the user.
#model IEnumerable<MVR.Models.ViewIndividual>
<h2>Level1</h2>
<select>
#foreach (var item in Model) {
<option value="#item.Case_Number">#item.Patient_Lastname ,
#item.Patient_Firstname
</option>
}
</select>
As always in an ASP.NET MVC application you start by defining a view model:
public class MyViewModel
{
public string SelectedIndividual { get; set; }
public SelectList Individuals { get; set; }
}
then you write a controller action that populates this view model from some data source or something:
public ActionResult Index()
{
// TODO : fetch those from your repository
var values = new[]
{
new { Value = "1", Text = "item 1" },
new { Value = "2", Text = "item 2" },
new { Value = "3", Text = "item 3" },
};
var model = new MyViewModel
{
Individuals = new SelectList(values, "Value", "Text")
};
return View(model);
}
and finally you have a strongly typed view using strongly typed helpers:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedIndividual,
Model.Individuals
)
This being said, because I see that you are not using any view models in your application, you could always try the following ugliness (not recommended, do this at your own risk):
#model IEnumerable<MVR.Models.ViewIndividual>
<h2>Level1</h2>
#Html.DropDownList(
"SelectedIndividual",
new SelectList(
Model.Select(
x => new {
Value = x.Case_Number,
Text = string.Format(
"{0}, {1}",
x.Patient_Lastname,
x.Patient_Firstname
)
}
),
"Value",
"Text"
)
)
Of course such pornography is not something that I would recommend to ever write in a view and I wouldn't recommend even to my worst enemies.
Conclusion: In an ASP.NET MVC application you should always be using view models and strongly typed views with strongly typed helpers (see first part of my answer).
Here is the full example
public class PageModel
{
[Display(Name = "Page ID")]
public Guid ID { get; set; }
[Display(Name = "Page Type ID")]
public Guid PageTypeID { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Page Type Name")]
public string PageTypeName { get; set; }
[Display(Name = "Html Content")]
public string HtmlContent { get; set; }
public SelectList PageTypeList { get; set; }
}
the C# code
public ActionResult Edit(Guid id)
{
var model = db.Pages.Where(p => p.ID == id).FirstOrDefault();
var typeList = new SelectList(db.PageTypes.OrderBy(s => s.Name).ToList(), "ID", "Name");
var viewModel = new PageModel { PageTypeList = typeList };
viewModel.HtmlContent = model.HtmlContent;
viewModel.ID = model.ID;
viewModel.PageTypeID = Guid.Parse(model.PageTypeID.ToString());
viewModel.Title = model.Title;
return View(viewModel);
}
[HttpPost]
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(PageModel page)
{
if (ModelState.IsValid)
{
var model = db.Pages.Where(p => p.ID == page.ID).FirstOrDefault();
model.Title = page.Title;
model.HtmlContent = page.HtmlContent;
model.PageTypeID = page.PageTypeID;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(page);
}
and lastly html
#model competestreet.com.Models.PageModel
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_LayoutCMS.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#HtmlContent').ckeditor();
});
</script>
<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>
<script src="#Url.Content("~/Scripts/ckeditor/ckeditor.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ckeditor/adapters/jquery.js")" type="text/javascript"></script>
<h2 class="title">
<span class="text-cms">CM<span>S</span></span></h2>
<div class="box">
<div class="t">
</div>
<div class="c">
<div class="content">
<div class="main-holder">
<div id="sidebar">
<ul>
<li>Home</li>
<li>Pages</li>
</ul>
</div>
<div id="content" style="min-height: 500px;">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Page Type - #Html.DropDownListFor(x => x.PageTypeID, Model.PageTypeList)
#Html.ValidationMessageFor(model => model.PageTypeID)</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title, new { #class = "text-box" })
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="clear">
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HtmlContent)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.HtmlContent, new { #name = "Editor1", #class = "Editor1" })
#Html.ValidationMessageFor(model => model.HtmlContent)
</div>
<div class="clear">
</div>
<p>
<input type="submit" value="Save" class="input-btn" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
</div>
</div>
<div class="b">
</div>
</div>

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