MVC Model on Post has no navigation properties - asp.net-mvc-3

I've looked around SO and I can't find anyone with an issue like this, so I'm posting this question.
I have a two edit actions in a controller (post and get) and in the GET I populate the Wine property of a viewmodel that gets passed to the view.
On the POST, I read that viewmodel, and save the changes to the database. After that I wanted to update my Lucene seach index with the updated Wine property. However, I keep getting an error because the Wine property doesn't have any of its navigation properties populated.
I tried looking up a new wine object using db.Wines.Find(ew.wine.WindID) but that still returns a Wine with no navigation properties. It is worth mentioning this is exactly what the GET edit action does, and the is populated correctly. I have no idea what is going on here. I also tried Wine w = db.Entry(ew.Wine).Entity to get those navigation properties populated, but to no avail... Thanks for the help in advance!
ViewModel & Wine Model
public class NewWineViewModel
{
public Wine Wine { get; set; }
public VOAVIRequest VOAVIRequest { get; set; }
public bool IsRequest { get; set; }
public SelectList VarTypes { get; set; }
public SelectList Origins { get; set; }
public SelectList Apps { get; set; }
public SelectList Vintages { get; set; }
public SelectList Importers { get; set; }
public NewWineViewModel()
{
this.Wine = new Wine();
}
}
public class Wine :Updater
{
public int WineID { get; set; }
//public int WineTypeID { get; set; }
[Display(Name = "Varietal/Type")]
public int? VarTypeID { get; set; }
[Display(Name = "Origin")]
public int? OriginID { get; set; }
[Display(Name = "Appellation")]
public int? AppID { get; set; }
[Display(Name = "Vintage")]
public int? VintageID { get; set; }
[Display(Name = "Importer")]
public int? ImporterID { get; set; }
public int ProducerID { get; set; }
public string Designate { get; set; }
[Display(Name = "Drink Window")]
public string DrinkWindow { get; set; }
public string Body { get; set; }
public string SKU { get; set; }
[Display(Name = "Varietal Makeup")]
public string VarietalMakeup { get; set; }
[Display(Name = "Case Production")]
public string CaseProduction { get; set; }
[Display(Name = "Alcohol Content")]
public double? AlcoholContent { get; set; }
public string Winemaker { get; set; }
[Display(Name = "Consulting Winemaker")]
public string ConsultWinemaker { get; set; }
public bool Sustainable { get; set; }
public bool Kosher { get; set; }
public bool Organic { get; set; }
public bool Biodynamic { get; set; }
public bool SalmonSafe { get; set; }
public Boolean Active { get; set; }
[Display(Name = "ResidualSugar")]
public double? RS { get; set; }
public double? pH { get; set; }
public string QRUrl { get; set; }
public virtual WineType WineType { get; set; }
public virtual VarType VarType { get; set; }
public virtual Origin Origin { get; set; }
public virtual App App { get; set; }
public virtual Vintage Vintage { get; set; }
public virtual Importer Importer { get; set; }
public virtual Producer Producer { get; set; }
}
Two Edit Actions from the controller:
[ProducerEdit]
public ActionResult Edit(int WineID)
{
NewWineViewModel ew = new NewWineViewModel();
ew.Wine = db.Wines.Find(WineID);
ew.VarTypes = new SelectList(db.VarTypes, "VarTypeID", "Name", ew.Wine.VarTypeID);
ew.Origins = new SelectList(db.Origins, "OriginID", "Name", ew.Wine.OriginID);
ew.Apps = new SelectList(db.Apps, "AppID", "Name", ew.Wine.AppID);
ew.Vintages = new SelectList(db.Vintages, "VintageID", "Name", ew.Wine.VintageID);
//might need to handle null on this one
ew.Importers = new SelectList(db.Importers, "ImporterID", "Name", ew.Wine.ImporterID);
return View(ew);
}
//post
[HttpPost]
[ProducerEdit]
public ActionResult Edit(NewWineViewModel ew)
{
if (ModelState.IsValid)
{
ew.Wine.Body = ew.Wine.Body == "Please select wine body" ? string.Empty : ew.Wine.Body;
ew.Wine.UpdatedBy = User.Identity.Name;
ew.Wine.UpdatedOn = DateTime.Now;
db.Entry(ew.Wine).State = EntityState.Modified;
db.SaveChanges();
Wine w = db.Wines.Find(ew.Wine.WineID);
Lucene.LuceneSearch.ClearLuceneIndexRecord(ew.Wine.WineID);
Lucene.LuceneSearch.AddUpdateLuceneIndex(ew.Wine);
if (ew.IsRequest)
{
ew.VOAVIRequest.WineID = ew.Wine.WineID;
ew.VOAVIRequest.CreatedBy = User.Identity.Name;
ew.VOAVIRequest.CreatedOn = DateTime.Now;
db.VOAVIRequests.Add(ew.VOAVIRequest);
db.SaveChanges();
return RedirectToAction("Requested");
//redirect to "Request Submitted" page for new wines
}
return RedirectToAction("Details", new { id = ew.Wine.WineID });
}
else
{
ew.VarTypes = new SelectList(db.VarTypes, "VarTypeID", "Name", ew.Wine.VarTypeID);
ew.Origins = new SelectList(db.Origins, "OriginID", "Name", ew.Wine.OriginID);
ew.Apps = new SelectList(db.Apps, "AppID", "Name", ew.Wine.AppID);
ew.Vintages = new SelectList(db.Vintages, "VintageID", "Name", ew.Wine.VintageID);
//might need to handle null on this one
ew.Importers = new SelectList(db.Importers, "ImporterID", "Name", ew.Wine.ImporterID);
return View(ew);
}
}
EDIT - here is the form in Razor
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<h3>#ViewBag.ProducerName</h3>
#Html.HiddenFor(m => m.Wine.WineID)
#Html.HiddenFor(m => m.Wine.ProducerID)
#Html.HiddenFor(m => m.IsRequest)
<h4 style="margin-top: -40px; padding-bottom: 10px;">Editing #Model.Wine.Name</h4>
<table>
<tr>
<td>#Html.LabelFor(m => m.Wine.VarTypeID)
</td>
<td style="display: inline">
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.VarTypeID, Model.VarTypes, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.VarType, new { style = "display: none;", #class = "voavignore" })
<a id="lnkNewVar" class="filetypes" href="#">New Varietal?</a> #* #Html.ValidationMessageFor(m => m.VOAVIRequest.VarType)*#
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.OriginID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.OriginID, Model.Origins, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.Origin, new { style = "display: none;", #class = "voavignore" })
<a id="lnkNewOrigin" class="filetypes" href="#">New Origin?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.AppID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.AppID, Model.Apps, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.App, new { style = "display: none;", #class = "voavignore" })<a
id="lnkNewApp" class="filetypes" href="#">New Varietal?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.VintageID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.VintageID, Model.Vintages, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.Vintage, new { style = "display: none;", #class = "voavignore" })
<a id="lnkNewVintage" class="filetypes" href="#">New Varietal?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Designate)
</td>
<td>
#Html.EditorFor(m => m.Wine.Designate)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.DrinkWindow)
</td>
<td>
#Html.EditorFor(m => m.Wine.DrinkWindow)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.VarietalMakeup)
</td>
<td>
#Html.EditorFor(m => m.Wine.VarietalMakeup)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Body)
</td>
<td>
#Html.DropDownListFor(m => m.Wine.Body, new SelectList(Model.Wine.BodyList, "Text", "Text", Model.Wine.Body), new { #class = "chzn-select" })
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.ImporterID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.ImporterID, Model.Importers, new { #class = "chzn-select" })</div>
#Html.TextBoxFor(m => m.VOAVIRequest.Importer, new { style = "display: none;" })
<a id="lnkNewImporter" class="filetypes" href="#">New Varietal?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.SKU)
</td>
<td>
#Html.EditorFor(m => m.Wine.SKU)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.CaseProduction)
</td>
<td>
#Html.EditorFor(m => m.Wine.CaseProduction)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.AlcoholContent)
</td>
<td>
#Html.EditorFor(m => m.Wine.AlcoholContent)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.RS)
</td>
<td>
#Html.EditorFor(m => m.Wine.RS)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.pH)
</td>
<td>
#Html.EditorFor(m => m.Wine.pH)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Winemaker)
</td>
<td>
#Html.EditorFor(m => m.Wine.Winemaker)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.ConsultWinemaker)
</td>
<td>
#Html.EditorFor(m => m.Wine.ConsultWinemaker)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Sustainable)
</td>
<td>
#Html.EditorFor(m => m.Wine.Sustainable)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Kosher)
</td>
<td>
#Html.EditorFor(m => m.Wine.Kosher)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Organic)
</td>
<td>
#Html.EditorFor(m => m.Wine.Organic)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Biodynamic)
</td>
<td>
#Html.EditorFor(m => m.Wine.Biodynamic)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.SalmonSafe)
</td>
<td>
#Html.EditorFor(m => m.Wine.SalmonSafe)
</td>
</tr>
</table>
<p>
<input type="submit" value="Update" />
</p>
}

Related

Partial View not showing data

I have a partial view which does not show the data. Here is a simple version. Here are my Models. The parent and child records
namespace Partial.Models
{
using System;
using System.Collections.Generic;
public partial class Parent
{
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Parent()
{
this.Children = new HashSet<Child>();
}
public int ID { get; set; }
public string Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Child> Children { get; set; }
}
}
namespace Partial.Models
{
using System;
using System.Collections.Generic;
public partial class Child
{
public int ID { get; set; }
public Nullable<int> ParentID { get; set; }
public string Description { get; set; }
public virtual Parent Parent { get; set; }
}
}
Here are my controllers which only involve the index and edit forms.
namespace Partial.Controllers
{
public class ParentsController : Controller
{
private PartialEntities db = new PartialEntities();
// GET: Parents
public ActionResult Index()
{
return View(db.Parents.ToList());
}
namespace Partial.Controllers
{
public class ChildrenController : Controller
{
private PartialEntities db = new PartialEntities();
// GET: Children
public ActionResult Index()
{
var children = db.Children.Include(c => c.Parent);
return View(children.ToList());
}
Here is my view. Parent Form which is the edit form. Which should display the children index form
#model Partial.Models.Parent
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Parent</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<table class="table">
<tr>
<td>
Html.Partial("~/Views/Children/Index.cshtml", new List<Partial.Models.Child> ());
</td>
</tr>
</table>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Child Form which should display the children but doesn't
#model IEnumerable<Partial.Models.Child>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Parent.Description)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Parent.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
Please Try Code
Remove the code
Html.Partial("~/Views/Children/Index.cshtml", new List<Partial.Models.Child> ());
replace Code
#{Html.RenderAction("Index","Children");}
Sysntext For :
#Html.RenderAction("Action name","Controller name",Route values)

Delete multiple rows in mvc don't work

I have class connection
public partial class Connections
{
public System.Guid IdConnection { get; set; }
[Required(ErrorMessage = "Requienter code hereenter code here`red")]
public string Sign { get; set; }
[DataType(DataType.Date)]
[Required(ErrorMessage = "Required")]
public System.DateTime Date { get; set; }
[DataType(DataType.Time)]
[Required(ErrorMessage = "Required")]
public System.DateTime Time { get; set; }
[Required(ErrorMessage = "Required")]
public double Band { get; set; }
[Required(ErrorMessage = "Required")]
public string Modulation { get; set; }
[Required(ErrorMessage = "Required")]
public int RST { get; set; }
public string Comment { get; set; }
[Required(ErrorMessage = "Required")]
public string QLS { get; set; }
}
Method in controller:
[HttpPost]
public ActionResult DeleteMultiple(System.Guid[] deleteInputs)
{
var db= new MainDbContext();
var connections = db.Connections.ToList();
if (deleteInputs == null)
{
}
foreach (var item in deleteInputs)
{
Connections con = db.Connections.Find(item);
db.Connections.Remove(con);
}
db.SaveChanges();
return RedirectToAction("EditDelete", "Connection");
}
and View:
#model IEnumerable<RadioSite.Connections>
#{
ViewBag.Title = "My connections";
}
<table class="table">
<tr>
<th>
Select
</th>
<th>
#Html.DisplayNameFor(model => model.Sign)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayNameFor(model => model.Time)
</th>
<th>
#Html.DisplayNameFor(model => model.Band)
</th>
<th>
#Html.DisplayNameFor(model => model.Modulation)
</th>
<th>
#Html.DisplayNameFor(model => model.RST)
</th>
<th>
#Html.DisplayNameFor(model => model.Comment)
</th>
<th>
#Html.DisplayNameFor(model => model.QLS)
</th>
<th colspan="2">
Actions
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="deleteInputs" id="deleteInputs" value="#item.IdConnection" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Sign)
</td>
<td>
#Html.ValueFor(modelItem => item.Date, "{0:dd/MM/yyyy}")
</td>
<td>
#Html.ValueFor(modelItem => item.Time, "{0:HH:MM}")
</td>
<td>
#Html.DisplayFor(modelItem => item.Band)
</td>
<td>
#Html.DisplayFor(modelItem => item.Modulation)
</td>
<td>
#Html.DisplayFor(modelItem => item.RST)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comment)
</td>
<td>
#Html.DisplayFor(modelItem => item.QLS)
</td>
<td>
#using (Html.BeginForm("Edit", "Connection", FormMethod.Get))
{
<input type="submit" value="Edit" formaction="/Connection/Edit/#item.IdConnection" />
}
</td>
<td>
#using (Html.BeginForm("DeleteItem", "Connection", FormMethod.Post))
{
<input type="submit" value="Delete" formaction="/Connection/DeleteItem/#item.IdConnection" />
}
</td>
</tr>
}
</table>
#using (Html.BeginForm("DeleteMultiple", "Connection", FormMethod.Post))
{
<input type="submit" value="Delete Selected"/>
}
I selected items in grid (checked checkbox) and in method :public ActionResult DeleteMultiple(System.Guid[] deleteInputs) array deleteInputs always is null.
Your html.beginform pointing to "DeleteMultiple" has nothing being passed to it! You need to either restructure your view to include the inputs in your form or, since this is a delete function, make an ajax call to your controller action and send in the values of the selected check boxes.

MVC 3 Model property is not being set in partial view called by html.action

I have an issue with my app, ill try explain by example, I have a form, this form exist of several textboxes and dropdown lists. For reusability I merged 3 drop down lists into a partial view, this partial view i load with #Html.Action, this works ok, when i start the form i see everything appears as it should be, although I dont know why but those required drop down lists directly are shown with red start and said it is required fields.
But when i fill everything in, and i select the values from the drop down lists, and i click on OK, the values from drop down lists are NULL.
I think it will be more comprehendable with a code example:
Main model:
public class FormModel
{
[Required]
public string UserName { get; set; }
[Required]
[Display(Name = "Birthdate")]
public DateTime? Birthdate { get; set; }
//This is what i'm talking about, that is not being set, the location
public Location Location { get; set; }
}
Here is the location class, which is then passed to the partial view and normally i think should be set, it looks like this:
public class Location
{
[Required]
[Display(Name = "Country")]
public string CountryId { get; set; }
[Required]
[Display(Name = "Region")]
public string RegionId { get; set; }
[Required]
[Display(Name = "City")]
public string CityId { get; set; }
}
Now we have a partial view for the location:
#model TestWebsite.Models.Location
<tr>
<td class="editor-label">
#Html.LabelFor(m => m.CountryId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.CountryId, Model.Countries, "---select--", null)
</td>
<td>
#Html.ValidationMessageFor(m => m.CountryId)
</td>
</tr>
<!-- Region -->
<tr>
<td class="editor-label">
#Html.LabelFor(m => m.RegionId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.RegionId, Enumerable.Empty<SelectListItem>(), "---select--", null)
</td>
<td>
#Html.ValidationMessageFor(m => m.RegionId)
</td>
</tr>
<!-- City -->
<tr>
<td class="editor-label">
#Html.LabelFor(m => m.CityId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.CityId, Enumerable.Empty<SelectListItem>(), "---select--", null)
</td>
<td>
#Html.ValidationMessageFor(m => m.CityId)
</td>
</tr>
Then we call this partial view in the forms like this:
#Html.Action("LocationGroup", "Account", Model.Location)
And finally in the controller:
[ChildActionOnly]
public ActionResult LocationGroup(Location model)
{
model.Countries = GetCountries();
return PartialView("_LocationView", model);
}
I know it is a lot of code, but i hope you could help me ...
I think you should use Editor Templates:
#model TestWebsite.Models.FormModel
#using(Html.BeginForm())
{
#Html.EditorFor(x => x.Location)
<input type="submit" value="save"/>
}
and add the partial inside ~/Views/[ControllerName]/EditorTemplates/Location.cshtml or ~/Views/Shared/EditorTemplates/Location.cshtml
code of template:
#model TestWebsite.Models.Location
<tr>
<td class="editor-label">
#Html.LabelFor(m => m.CountryId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.CountryId, Model.Countries, "---select--", null)
</td>
<td>
#Html.ValidationMessageFor(m => m.CountryId)
</td>
</tr>
<!-- Region -->
<tr>
<td class="editor-label">
#Html.LabelFor(m => m.RegionId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.RegionId, Enumerable.Empty<SelectListItem>(), "---select--", null)
</td>
<td>
#Html.ValidationMessageFor(m => m.RegionId)
</td>
</tr>
<!-- City -->
<tr>
<td class="editor-label">
#Html.LabelFor(m => m.CityId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.CityId, Enumerable.Empty<SelectListItem>(), "---select--", null)
</td>
<td>
#Html.ValidationMessageFor(m => m.CityId)
</td>
</tr>
But if you prefer to have partial in some location (not follow conventions) you could specify the location:
#Html.EditorFor(x => x.Location, "~/Views/SpecifyLocation/_Location.cshtml")
I agree with Xordal, EditorTemplates are the way to go. Incredibly useful stuff. One thing I noticed the lack of a SelectList. I may be missing something here, but have you tried the following?:
<td class="editor-label">
#Html.LabelFor(m => m.CountryId)
</td>
<td class="editor-field">
#Html.DropDownListFor(m => m.CountryId, new SelectList(Model.Countries, "CountryId" , "CountryName", null))
</td>
<td>
#Html.ValidationMessageFor(m => m.CountryId)
</td>
Try Html.RenderPartial instead of Html.Action

selected value in dropdownlist is not working

I am trying to display a complex viewmodel in a view, everything works fine except one dropdownlist. I am displaying a list of enum, and set the selected object as it should be. But for an unknown reason, its not showing the selected value. I have tried many times with but failed -- please help me. The code is given below -
Enum:
public enum CommentStatus
{
NoStatus = 0,
Resolved = 1,
NotApplicable = 2
}
Model:
public class CheckComments
{
public string EntryId { get; set; }
public int Serial { get; set; }
public string Comment { get; set; }
public DateTime CommentDate { get; set; }
public CommentStatus CommentStatus { get; set; }
}
public class CheckDataViewModel
{
public string EntryId { get; set; }
public string CheckId { get; set; }
public decimal Value { get; set; }
public List<CheckComments> CheckCommentsList { get; set; }
public List<string> CommentStatusList { get; set; }
}
Controller:
public class CheckDataController : Controller
{
public ActionResult GetEnteredCheckData(string entryId)
{
var checkDataViewModel = new CheckDataViewModel();
var checkData = new CheckDataManager().GetCheckData(entryId);
checkDataViewModel.EntryId = checkData.EntryId;
checkDataViewModel.CheckId = checkData.CheckId;
checkDataViewModel.Value = checkData.Value;
checkDataViewModel.CheckCommentsList = checkData.Comments;
checkDataViewModel.CommentStatusList = Enum.GetNames(typeof (CommentStatus)).ToList();
return View("EnteredCheckData", checkDataViewModel);
}
}
View:
#model PDCA.Web.Models.CheckDataViewModel
#{
ViewBag.Title = "EnteredCheckData";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.EntryId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.EntryId)
#Html.HiddenFor(model => model.EntryId)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Check Information</legend>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.CheckId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.Check.CheckId)
#Html.HiddenFor(model => model.Check.CheckId)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Comments</legend>
<div>
<table class="table table-bordered">
<tr>
<th>
Serial
</th>
<th>
Comment
</th>
<th>
Date
</th>
<th>
Status
</th>
<th>
</th>
</tr>
#for (int i = 0; i < Model.CheckCommentsList.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Serial)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Serial)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Comment)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Comment)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].CommentDate)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].CommentDate)
</td>
<td>
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus))
#Html.ValidationMessageFor(model => Model.CheckCommentsList[i].CommentStatus)
</td>
<td>
#Html.ActionLink("Update Status", "UpdateCommentStatus", new { Model.EntryId, Model.CheckCommentsList[i].Serial, Model.Check.CheckTitle, Model.Check.CheckId })|
#Html.ActionLink("Delete", "DeleteComment", new { Model.CheckCommentsList[i].Serial, Model.EntryId })
</td>
</tr>
}
</table>
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The code is too lengthy but I think this will help you to understand my mistakes. Thanks in advance friends.
Solution:
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus.ToString()))

Required Validation Error Message is not getting displayed in jquery popup modal form

I have used ComponentModel.DataAnnotations [Required] attribute for validation messages. The message is not getting displayed in my form. However, the RegularExpression validation and Range validation are working fine.
In one of my field, I used both [Required] and [RegualarExpression]. When I give the wrong input in the text box, the RegualarExpression validation message appears and after erasing the input, then only Required validation message. Otherwise, Required validation message does not appear.
Here is my code:
--Model Class
public class Email
{
[Required(ErrorMessage = "Email Address is required!")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9] {1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "Invalid Email Address.")]
public virtual string EmailAddress { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "First Name is Required")]
public virtual string FirstName { get; set; }
public virtual string MiddleName { get; set; }
[Required(ErrorMessage = "Last Name is required!")]
public virtual string LastName { get; set; }
public virtual string Status { get; set; }
}
--View
#{Html.EnableClientValidation();}
<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("CreateEmail", "LeaderBoard", FormMethod.Post, new { enctype = "multipart/form-data", id = "create-email-dialog" }))
{
#Html.ValidationSummary(true)
{
<form>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="popTable">
<tr>
<td width="38%">
First Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Middle Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.MiddleName)
#Html.ValidationMessageFor(model => model.MiddleName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Last Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Email Address:
</td>
<td width="62%">
<div class="errorMessage">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
</td>
</tr>
<tr>
<td width="38%">
Status:
</td>
<td width="62%">
<div class="editor-field">
#Html.DropDownList("Status", ViewData["Status"] as SelectList)
</div>
</td>
</tr>
</table>
<input type="button" id="btnCreateEmail" value="Save" name="submit" class="btn" />
<input type="button" value="Cancel" name="cancel" class="closeDialog" />
</form>
}
}
--Controller
[HttpGet]
public ActionResult CreateEmail()
{
if (Request.IsAjaxRequest())
{
var list = new SelectList(new[]
{
new{Id = "Active", Name = "Active"},
new{Id = "Inactive", Name = "Inactive"}
},
"Id", "Name", 1);
ViewData["Status"] = list;
return PartialView("_CreateEmail");
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult CreateEmail(Email model)
{
using (_emailRepository)
{
if (ModelState.IsValid)
{
_emailRepository.Create(model);
return Json(new { success = true });
}
return RedirectToAction("Index");
}
}
Validate those fields in the document ready function
$( document ).ready( function ( e )
{
$( "form" ).validate().element( "#FirstName" );
$( "form" ).validate().element( "#LastName" );
});

Resources