html.dropdownlist MVC3 confusion - asp.net-mvc-3

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>

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

MVC 5 Using POSTAL with Models

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

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.

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() );
});
});
});

mvc3 razor dropdownlistfor causing update model to fail

I have a problem with the following code. Basically when I call updatemodel it fails but I dont get an inner exception. If i change the drop down to a text box it works.
class:
public class Member
{
[Key]
public int MemberID { get; set; }
[StringLength(50),Required()]
public string Name { get; set; }
[Range(0,120)]
public short Age { get; set; }
[Required(),MaxLength(1)]
public string Gender {get; set;}
[Required()]
public virtual Team Team { get; set; }
}
controller methods:
[HttpGet]
public ActionResult ViewMember(int id)
{
try
{
var m = db.GetMember(id);
var maleItem = new SelectListItem{Text = "Male", Value= "M", Selected=m.Gender == "M"};
var femaleItem = new SelectListItem{Text = "Female", Value="F", Selected=m.Gender == "F"};
List<SelectListItem> items = new List<SelectListItem>();
items.Add(maleItem);
items.Add(femaleItem);
var genders = new SelectList(items, "Value", "Text");
ViewBag.Genders = genders;
return View(m);
}
catch (Exception ex)
{
return View();
}
}
[HttpPost]
public ActionResult ViewMember(Member m)
{
try
{
var member = db.GetMember(m.MemberID);
m.Team = db.GetTeam(member.Team.TeamID);
UpdateModel(member);
db.Save();
return RedirectToAction("ViewMembers", new { id = member.Team.TeamID });
}
catch (Exception ex)
{
return View();
}
}
and finally cshtml code:
#model GreenpowerAdmin.Models.Member
#using GreenpowerAdmin.Helpers
#{
ViewBag.Title = "ViewMember";
}
<h2>ViewMember</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>Member</legend>
#Html.HiddenFor(model => model.MemberID)
<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.Team.Name)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.Team.Name)
#Html.ValidationMessageFor(model => model.Team.Name)
</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>
<div class="editor-label">
#Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
#Html.DropDownList("Gender", ViewBag.Genders as SelectList)
#Html.ValidationMessageFor(model => model.Gender)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "ViewMembers", new { id=Model.Team.TeamID })
</div>
When I click the save button the updatemodel line fails. As said above, it doesn't fail if I use a text box for gender. Does anyone know what is making it fail or how to debug it?
Try declaring the MemberID property as a nullable integer:
[Key]
public int? MemberID { get; set; }

Resources