validations error messages not showing on the view - asp.net-mvc

I have implemented a mvc kendo window control in my MVC page and the form validation doenst seem to work. I can the model state as false in the controller but the view doesnt seem showing the messages. Please note here that WorkLogType,WorkLog Subject and Details are required field. I have set the required attribute in the view model. I have also set the validation tag in the view for the respective controls. What is the problem ?
Here is my code
View
#using (Ajax.BeginForm("ActivityWorkLog_Create", "Activity", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
}))
{
<div class="k-popup-edit-form k-window-content k-content" data-role="window">
<div class="k-edit-form-container">
#Html.HiddenFor(x => x.RequestID, new { data_bind = "value: requestId" })
#Html.HiddenFor(x => x.ActivityID, new { data_bind = "value: activityId" })
#Html.HiddenFor(x => x.CountryCode, new { data_bind = "value: countryCode" })
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogAppliesToName)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.WorkLogAppliesToName)
.Name("WorkLogAppliesToID")
.Filter("contains")
.HtmlAttributes(new { style = "width:300px", #readonly = "readonly" })
.Placeholder("Select...")
.DataTextField("WorkLogAppliesToName")
.DataValueField("WorkLogAppliesToID")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetWorkLogAppliesTo", "WorkLog", new { id = 0 }).Type(HttpVerbs.Post)
)
)
)
#Html.ValidationMessageFor(model => model.WorkLogAppliesToName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.ActivitySLA)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.ActivitySLA)*#
#Html.TextBoxFor(model => model.ActivitySLA, new { id = "ActivityDesc", #readonly = "readonly", Class = "textBoxFor" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.ActivityID)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.ActivityID)
.Name("Activity")
.Filter("contains")
.HtmlAttributes(new { style = "width:300px", #readonly = "readonly" })
.Placeholder("Select...")
.DataTextField("Description")
.DataValueField("ActivityID")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetActivity", "WorkLog").Data("additionalActivityInfo").Type(HttpVerbs.Post)
)//.ServerFiltering(true)
)//.CascadeFrom("ServiceID").Filter("contains")
)
#Html.ValidationMessageFor(model => model.ServiceID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogType)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.WorkLogType)
.Name("WorkLogTypeCode")
.Filter("contains")
.HtmlAttributes(new { style = "width:300px" })
.Placeholder("Select...")
.DataTextField("WorkLogType")
.DataValueField("WorkLogTypeCode")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetWorkLogType", "WorkLog").Data("additionalWLTInfo").Type(HttpVerbs.Post))
)
)
#Html.ValidationMessageFor(model => model.WorkLogType, "Please select a worklog type", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogSubject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WorkLogSubject)
#Html.ValidationMessageFor(model => model.WorkLogSubject, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogDetails)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.WorkLogDetails, new { htmlAttributes = new { #class = "form-control", cols = "50" } })
#Html.ValidationMessageFor(model => model.WorkLogDetails, "", new { #class = "text-danger" })
</div>
</div>
<div class="worklogStatusButtonAlign">
<button id="btnWorkLogSave" type="submit" class="k-button k-button-icontext k-primary k-grid-update">Save</button>
<button id="btnClose" type="button" class="k-button k-button-icontext k-grid-cancel">Cancel</button>
</div>
<div id="statusMessage"> </div>
</div>
</div>
}
ViewModel
public class ActivityWorkLogViewModel
{
[ScaffoldColumn(false)]
[Display(Name = "WorkLogID", ResourceType = typeof(Resources.Resource))]
public int WorkLogID { get; set; }
[Required]
[Display(Name = "WorkLogTypeCode", ResourceType = typeof(Resources.Resource))]
public string WorkLogTypeCode { get; set; }
[Display(Name = "WorkLogType", ResourceType = typeof(Resources.Resource))]
[Required(ErrorMessage = "WorkLogType is required")]
public string WorkLogType { get; set; }
[Required]
[Display(Name = "WorkLogAppliesToID", ResourceType = typeof(Resources.Resource))]
public int WorkLogAppliesToID { get; set; }
[Display(Name = "WorkLogAppliesToName", ResourceType = typeof(Resources.Resource))]
public string WorkLogAppliesToName { get; set; }
[Required]
[Display(Name = "RequestID", ResourceType = typeof(Resources.Resource))]
public int RequestID { get; set; }
[Display(Name = "ServiceID", ResourceType = typeof(Resources.Resource))]
public Nullable<int> ServiceID { get; set; }
[Display(Name = "ActivityID", ResourceType = typeof(Resources.Resource))]
public Nullable<int> ActivityID { get; set; }
[Required(ErrorMessage = "Subject is required")]
[Display(Name = "WorkLogSubject", ResourceType = typeof(Resources.Resource))]
public string WorkLogSubject { get; set; }
[Required(ErrorMessage = "Details is required")]
[Display(Name = "WorkLogDetails", ResourceType = typeof(Resources.Resource))]
public string WorkLogDetails { get; set; }
[Display(Name = "EmailTo", ResourceType = typeof(Resources.Resource))]
public string EmailTo { get; set; }
[Display(Name = "IsActive", ResourceType = typeof(Resources.Resource))]
public bool IsActive { get; set; }
[Display(Name = "CountryCode", ResourceType = typeof(Resources.Resource))]
public string CountryCode { get; set; }
[Display(Name = "ActivitySLA", ResourceType = typeof(Resources.Resource))]
public string ActivitySLA { get; set; }
}
Controller
[HttpPost]
public ActionResult ActivityWorkLog_Create(ActivityWorkLogViewModel workLogViewModel)
{
if (!ModelState.IsValid)
{
return View("EditorTemplates/_WorkLogEdit", Mapper.Map<ActivityWorkLogViewModel>(workLogViewModel));
}
WorkLogRepository workLogRepository = new WorkLogRepository();
workLogRepository.CreateWorkLog(Mapper.Map<WorkLog>(workLogViewModel));
return PartialView("EditorTemplates/_WorkLogEdit", Mapper.Map<ActivityWorkLogViewModel>(workLogViewModel));
}
Bundle.config
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-1.12.1.min.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.min.js"
));

Add these lines in your view:
<script>
$(document).ready(function() {
var form = $('form') // Give Id prop to your from
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
<script>
Also make sure you add jquery.validate.js and jquery.validate.unobtrusive.js into your View cshtml for validation to work properly.

Related

how can I pass the context from both the class in the MODEL to one view without this error?

In a MODEL, I have two class - ContentDetails and CompetencyDetails which contains its properties
namespace CompetencyAssessmentServices.ServiceModel
{
public class ContentDetails
{
public int CaseStudyId { get; set; }
public string CaseStudy { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public bool IsActive { get; set; }
public bool ReviewStatus { get; set; }
public string SolutionDescription { get; set; }
public int CompetencyID { get; set; }
public string CompetencyName { get; set; }
public List<string> SolutionId { get; set; }
}
public class CompetencyDetails
{
public int CompID { get; set; }
public string CompName { get; set; }
}
}
Controller :
Action CaseStudy is retrieving the list of CompetencyDetails from database which is working fine.
namespace CompetencyAssessment.Controllers
{
public class ContentManagementController : Controller
{
// GET: ContentManagement
IContentManagementRepository repo = new ContentManagementRepository();
[HttpGet]
public ActionResult CaseStudy()
{
List<CompetencyDetails> complst = repo.GetCompetencyDetails();
ViewBag.list = complst;
return View(ViewBag.list);
}
[HttpPost]
public ActionResult CaseStudy(ContentDetails cd)
{
ContentDetails ctd = repo.CaseStudyCreationDetails(cd);
return View();
}
}
}
While loading the View, I am getting below error
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[CompetencyAssessmentServices.ServiceModel.CompetencyDetails]', but this dictionary requires a model item of type 'CompetencyAssessmentServices.ServiceModel.ContentDetails'.
View is
#model CompetencyAssessmentServices.ServiceModel.ContentDetails
#{
ViewBag.Title = "CASE-STUDY Contenet Creation (By SME)";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CASE-STUDY Contenet Creation (By SME)</title>
</head>
<body>
#using (Html.BeginForm())
{
<h4>ContentDetails</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.CaseStudy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.CaseStudy, new { htmlAttributes = new { #class = "form-control", style = "rows=20,columns=400" } })
#Html.ValidationMessageFor(model => model.CaseStudy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsActive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsActive)
#Html.ValidationMessageFor(model => model.IsActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
Solution 1: #Html.TextBox("Sol1") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
Solution 2: #Html.TextBox("Sol2") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
Solution 3: #Html.TextBox("Sol3") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
Solution 4: #Html.TextBox("Sol4") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
<div class="form-group">
#Html.LabelFor(model => model.SolutionId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SolutionId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SolutionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SolutionDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SolutionDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SolutionDescription, "", new { #class = "text-danger" })
</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>
}
</body>
</html>
The reason, I am getting this error because my view contains the reference from both class CompetencyDetails and ContentDetails
Can someone please help on how can I pass the context from both the class in the MODEL without this error ?
PS: This is my first MVC project so would appreciate any various approaches to achieve this
you can create new class having both the model class like example given below
public class Combine
{
public List<ContentDetails> ContentDetailsList { get; set; }
public ContentDetails ContentDetailsData { get; set; }
public List<CompetencyDetails> CompetencyDetailsInfoList { get; set; }
public CompetencyDetails CompetencyDetailsData { get; set; }
}
then in MVC controller
[HttpGet]
public ActionResult CaseStudy()
{
var caseStudy = new SupplierDTO()
{
ContentDetailsList = db.ContentDetails.ToList(),
CompetencyDetailsInfoList = db.CompetencyDetails.ToList(),
};
return View(caseStudy);
}
then MVC View
#model CompetencyAssessmentServices.Models.Combine
<div class="form-group">
#Html.LabelFor(model => model.ContentDetailsData.CaseStudy, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.ContentDetailsData.CaseStudy, new { htmlAttributes = new { #class = "form-control"} })
#Html.ValidationMessageFor(model => model.ContentDetailsData .CaseStudy, "", new { #class = "text-danger"})
</div>
</div>

Save List of object in MVC 5

Following are my two connected models.
When I post data with single Invoice and multiple Invoice_Details entry,
I found Invoice_Details blank inside Invoice object.
I am using EditorTemplate as you can see in below code.
How can I save single Invoice and Multiple Invoice_Details entry.
Invoice
public class Invoice
{
[UIHint("Invoice_Details")]
public virtual List<Invoice_Details> Invoice_Details { get; set; }
public Invoice()
{
Invoice_Details = new List<Models.Invoice_Details>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DATE { get; set; }
[Key]
[Display(Name = "Invoice no")]
[Required]
public int INVOICENO { get; set; }
[Display(Name = "Party")]
public int PARTY { get; set; }
[Display(Name = "Broker")]
public int BROKER { get; set; }
[Display(Name = "Terms")]
[Required]
public int TERMS { get; set; }
[Display(Name = "Brokerage")]
[Required]
public decimal BROKERAGE { get; set; }
[Display(Name = "Article")]
[Required]
public string ARTICLE { get; set; }
[Display(Name = "Total")]
public decimal TOTAL { get; set; }
[Display(Name = "Details")]
public string DETAILS { get; set; }
[ScaffoldColumn(false)]
public DateTime CREATE_TIMESTAMP { get; set; }
[ScaffoldColumn(false)]
public DateTime LAST_EDIT_TIMESTAMP { get; set; }
}
Invoice_Details
public class Invoice_Details
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name = "Invoice no")]
[Required]
public int INVOICENO { get; set; }
[Display(Name = "Caret")]
public decimal CARET { get; set; }
[Display(Name = "Price")]
public decimal PRICE { get; set; }
[Display(Name = "Rs/Dollar")]
[Required]
public string RUPEESDOLLAR { get; set; }
[Display(Name = "Rate")]
[Required]
public decimal RATEIFDOLLAR { get; set; }
[Display(Name = "Total")]
public decimal TOTAL { get; set; }
[ScaffoldColumn(false)]
public DateTime CREATE_TIMESTAMP { get; set; }
[ScaffoldColumn(false)]
public DateTime LAST_EDIT_TIMESTAMP { get; set; }
public virtual Invoice invoice { get; set; }
}
CREATE VIEW
#model SKUMAR.Models.Invoice
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Invoice</h4>
<hr />
<div class="col-md-6">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.INVOICENO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.INVOICENO, new { htmlAttributes = new {#autofocus="autofocus", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.INVOICENO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DATE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.DATE,new {#Value=ViewBag.CURRENTDATE, #class = "form-control" } )
#Html.ValidationMessageFor(model => model.DATE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PARTY, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PARTY, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PARTY, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BROKER, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BROKER, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BROKER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TERMS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TERMS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TERMS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BROKERAGE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BROKERAGE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BROKERAGE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ARTICLE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ARTICLE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ARTICLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TOTAL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TOTAL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TOTAL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DETAILS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DETAILS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DETAILS, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
#Html.EditorFor(m=>m.Invoice_Details)
</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>
Invoice_Details.cshtml EditorTemplate
#model SKUMAR.Models.Invoice_Details
<table class="table table-bordered table-hover">
<tr>
<td>#Html.TextBoxFor(m=>m.CARET, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.PRICE, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.RUPEESDOLLAR, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.RATEIFDOLLAR, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => m.TOTAL, new { #class = "form-control" })</td>
</tr>
</table>
Inside Invoice_Details.cshtml EditorTemplate instead of #model SKUMAR.Models.Invoice_Details , use #model SKUMAR.Models.Invoice and then change every line based on that. For example change #Html.TextBoxFor(m=>m.CARET to #Html.TextBoxFor(m=>m.Invoice_Details.CARET.

Query with linq from database

I'm doing an mvc Theater project with entity framework code first.
I created a page to add a movie to my database.
the Movie class has a Genre property,the Genre class has an Id and a Name property.
What I'm trying to do is query all rows of the Genres table from database with Linq (if other method is better do tell) and choose one Genre to connect to a row of the movie I'm creating.
thanks,any help is appreciated.
this is my Genre class
public class Genre
{
[Key]
public int Id { get; set; }
[Display(Name="Ganre")]
public string GenreName { get; set; }
public virtual ICollection<Movie> MoviesByGenre { get; set; }
}
this is my Movie class
public class Movie
{
[Key]
public string Id { get; set; }
[Required(ErrorMessage = "Movie name is required")]
[Display(Name="Movie name")]
public string MovieName { get; set; }
[Required(ErrorMessage = "Movie length is required")]
[Display(Name="Length(minutes)")]
public int LengthInMinutes { get; set; }
[Required(ErrorMessage="Genre of the movie is required")]
[Display(Name="Genre")]
public virtual Genre MovieGenre { get; set; }
public string Description { get; set; }
[Required(ErrorMessage = "Year of release is required")]
public int Year { get; set; }
[Required(ErrorMessage="Who is the director?")]
public virtual MovieDirector Director { get; set; }
public virtual MoviePoster Poster { get; set; }
//How many users bought a ticket
public virtual ICollection<ApplicationUser> UsersWhoBoughtTicket { get; set; }
}
this is the Add Movie page
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.MovieName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MovieName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MovieName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LengthInMinutes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LengthInMinutes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LengthInMinutes, "", new { #class = "text-danger" })
</div>
</div>
<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">
#Html.LabelFor(model => model.Year, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Year, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Year, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MovieGenre.GenreName, htmlAttributes: new { #class = "btn control-label col-md-2" })
<div class="col-md-10">
#Html.ValidationMessageFor(model => model.MovieGenre.GenreName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Director, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director, new { htmlAttributes = new { #class = "form-control dropdown" } })
#Html.ValidationMessageFor(model => model.Director, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Poster, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="Image" type="file" />
#Html.ValidationMessageFor(model => model.Poster)
</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>
I hope your entities are like this:
public class Genre
{
public int Id{ get; set; }
public string Name{ get; set; }
public ICollection<Movie> Movies{ get; set; }
}
public class Movie
{
public int Id{ get; set; }
public string Name{ get; set; }
public int GenreId {get; set; }
public Genre Genre{ get; set; }
}
Now your query would be like this:
_context.Include(x=>x.Movies).Genres; //it will return all genres with movies
_context.Movies.where(x=>x.GenreId == genreId); // it will return movies based on a genre id

Why if statement always returns false in asp.net mvc when updating data?

I used this code to update user's data in asp.net mvc 5 I think every thing is OK , but I don't know why I'm getting error message and data didn't saved and if (ModelState.IsValid) in Controller is false always .
Could anyone help me please ?
Admin Controller
[HttpGet]
public ActionResult EditUser(int id)
{
var load = db.Users.Find(id);
return View(load);
}
private const string _ImagesPathUser = "~/Images/User";
[HttpPost]
public ActionResult EditUser(User user, HttpPostedFileBase UploadImage)
{
if (ModelState.IsValid) // always returns false
{
UserRepositories blUser = new UserRepositories();
if (UploadImage != null)
{
// Delete exiting file
System.IO.File.Delete(Path.Combine(Server.MapPath(_ImagesPathUser), user.UserImage));
// Save new file
string fileName = Guid.NewGuid() + Path.GetFileName(UploadImage.FileName);
string path = Path.Combine(Server.MapPath(_ImagesPathUser), fileName);
UploadImage.SaveAs(path);
user.UserImage = fileName;
}
if (blUser.Update(user))
{
return JavaScript("alert(' added');");
}
else
{
return JavaScript("alert(' didn't add');");
}
}
else
{
return JavaScript("alert('Error');");
}
}
UserRepositories.cs
public bool Delete(int id, bool autoSave = true)
{
try
{
var entity = db.Users.Find(id);
db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
if (autoSave)
{
bool result = Convert.ToBoolean(db.SaveChanges());
if (result)
{
try
{
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\User\\" + entity.UserImage) == true)
{
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\User\\" + entity.UserImage);
}
}
catch { }
}
return result;
}
else
return false;
}
catch
{
return false;
}
}
EditUser.cs
#model NP1.Models.User
#{
ViewBag.Title = "EditUser";
Layout = "~/Views/Admin/AdminLayout.cshtml";
}
<h2>EditUser</h2>
#using (Html.BeginForm("EditUser", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm5" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserID)
<div class="form-group">
#Html.LabelFor(model => model.UserEmail, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserEmail)
#Html.ValidationMessageFor(model => model.UserEmail)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserFirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserFirstName)
#Html.ValidationMessageFor(model => model.UserFirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserLastName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserLastName)
#Html.ValidationMessageFor(model => model.UserLastName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserPassWord, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserPassWord)
#Html.ValidationMessageFor(model => model.UserPassWord)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserCellPhone, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserCellPhone)
#Html.ValidationMessageFor(model => model.UserCellPhone)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserTell, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserTell)
#Html.ValidationMessageFor(model => model.UserTell)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserImage, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ImageFor(model => model.UserImage, new { width = "300" }, "", "Images", "User")
#Html.Upload("UploadImage")
#Html.HiddenFor(model => model.UserImage)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserAddress, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserAddress)
#Html.ValidationMessageFor(model => model.UserAddress)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserBirthDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserBirthDate)
#Html.ValidationMessageFor(model => model.UserBirthDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserGender, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserGender)
#Html.ValidationMessageFor(model => model.UserGender)
</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>
}
User.cs
public partial class User
{
public int UserID { get; set; }
public string UserEmail { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserPassWord { get; set; }
public string UserCellPhone { get; set; }
public string UserTell { get; set; }
public string UserImage { get; set; }
public string UserAddress { get; set; }
public Nullable<byte> UserStatus { get; set; }
public Nullable<System.DateTime> UserBirthDate { get; set; }
public string UserGender { get; set; }
}
UserMetaData.cs
internal class UserMetaData
{
[ScaffoldColumn(false)]
[Bindable(false)]
public int UserID { get; set; }
[Required(ErrorMessage = "enter email", AllowEmptyStrings = false)]
[DisplayName("email")]
[Display(Name = "email")]
[RegularExpression(#"^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$", ErrorMessage = "enter correct email")]
public string UserEmail { get; set; }
[Required(ErrorMessage = "enter your name", AllowEmptyStrings = false)]
[DisplayName("name")]
[Display(Name = "name")]
[StringLength(50, ErrorMessage = "should be 50")]
public string UserFirstName { get; set; }
[Required(ErrorMessage = "enter your last name", AllowEmptyStrings = false)]
[DisplayName("last name")]
[Display(Name = "last name")]
[StringLength(50, ErrorMessage = "should be 50")]
public string UserLastName { get; set; }
[Required(ErrorMessage = "enter password", AllowEmptyStrings = false)]
[Display(Name = "password")]
[DisplayName("password")]
[DataType(DataType.Password)]
public string UserPassWord { get; set; }
[Display(Name = "mobile")]
[DisplayName("mobile")]
[RegularExpression(#"^0?9[123]\d{8}$", ErrorMessage = "enter mobile correct")]
[StringLength(11, ErrorMessage = "should be 11")]
public string UserCellPhone { get; set; }
[Display(Name = "tel")]
[DisplayName("tel")]
[StringLength(11, ErrorMessage = "should be 11")]
public string UserTell { get; set; }
public string UserImage { get; set; }
public string UserAddress { get; set; }
[ScaffoldColumn(false)]
[Display(Name = "status")]
[DisplayName("status")]
public Nullable<byte> UserStatus { get; set; }
[Display(Name = "BirthDate")]
[DisplayName("BirthDate")]
public Nullable<System.DateTime> UserBirthDate { get; set; }
[Display(Name = "gender")]
[DisplayName("gender")]
public string UserGender { get; set; }
}
}
namespace NP1.Models
{
[MetadataType(typeof(NP1.Models.MetaData.UserMetaData))]
public partial class User
{
[Required(ErrorMessage = "enter your pass", AllowEmptyStrings = false)]
[Display(Name = "repeate pass")]
[DisplayName("repeate pass")]
[DataType(DataType.Password)]
[Compare("UserPassWord", ErrorMessage = "not equal")]
public string UserConfirmPassWord { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
For debugging purposes you can add this code to your action:
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
//if you have some kind of logger use it here to get error data
// if not:
var e = error;
}
}
Put a break point on var e = error; line and check this error object for more info
You have few validations on each of the input elements in the model which might not be matching with database constraints.
Please debug the line ModelState.Isvalid, and use a quick watch to drilldown the errors/values details if any.
Alternatively, use below line in controller method to check for errors with model response due to input values
var errors = ModelState.Values.SelectMany(v => v.Errors);
Check if this helps you.

ASP Net MVC - Forms Validation on the ViewModel

I have a form which has a ViewModel class underlaying it. I have set the [Required] validation on fields of the form. The form still submits even though it does for a moment - before it submits - displays the ErrorMessage set on particular fields.
There is no validation on the StockReceipt model itself, but only the ViewModel. I looked at this question here and learnt that validating the model is optional.
I wonder why the form still submits when there are invalid input?
Here is my View and ViewModel code:
View:
#using (Html.BeginForm("SaveSettings", "StockReceipt", FormMethod.Post,
new { id = "StockReceiptForm", enctype = "multipart/form-data" }))
{
<fieldset>
<div>
#* #Html.ValidationSummary(false)*#
<legend>Stock-Receipt Details</legend>
#*#if (User.IsInRole(Constants.Super))
{*#
<div style="display: none;">
Delivery Note Ref
</div>
<div style="display: none;">
#Html.TextBoxFor(model => model.StockReceiptID, new { #Class = "k-textbox" })
</div>
<div class="editor-label">
Supplier
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.SupplierID).BindTo(Model.SuppliersList).DataTextField("Name").DataValueField("SupplierID").OptionLabel("Select")
#Html.ValidationMessageFor(model => model.SupplierID)
</div>
<div class="editor-label">
Material
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.MaterialID).BindTo(Model.MaterialsList).DataTextField("Name").DataValueField("MaterialID").OptionLabel("Select")
#Html.ValidationMessageFor(model => model.MaterialID)
</div>
<div class="editor-label">
Qty
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Quantity, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.Quantity)
</div>
<div class="editor-label">
Of which reserved
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.QuantityReserved, new { #Class = "k-textbox" })
</div>
<div class="editor-label">
Units
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.NumberOfUnits, new { #Class = "k-textbox" })
#(Html.Kendo().DropDownListFor(model => model.StockUnitsEnum).Name("StockUnitsEnum")
.BindTo(Enum.GetValues(typeof(StockUnitsEnum))
.Cast<StockUnitsEnum>()
.Select(p => new SelectListItem
{
Text = p.ToString(),
Value = ((int)p).ToString(CultureInfo.InvariantCulture)
})
.ToList())
)
#Html.ValidationMessageFor(model => model.NumberOfUnits)
</div>
<div class="editor-label">
Batch Reference:
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.BatchReference, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.BatchReference)
</div>
<div class="editor-label">
Slab Width
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.SlabWidth, new { #Class = "k-textbox" }) x #Html.TextBoxFor(model => model.SlabHeight, new { #Class = "k-textbox" })
</div>
<div class="editor-label">
Include Transport:
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.IncludeTransport)
</div>
<div class="editor-label">
Notes
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Notes, new { #Class = "k-textbox" })
</div>
<div class="clear">
Totals
</div>
<div class="editor-label">
Unit Cost
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.UnitCost, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.UnitCost)
</div>
<div class="editor-label">
Units
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.NumberOfUnits, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.NumberOfUnits)
</div>
<div class="editor-label">
Slab Cost
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.SlabCost, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.SlabCost)
</div>
<div class="editor-label">
Location
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.LocationID).BindTo(Model.LocationsList).DataTextField("Name").DataValueField("LocationID").OptionLabel("Select")
</div>
<div class="editor-label">
Purchase-Order Ref.
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.PurchaseOrderID).BindTo(Model.PurchaseOrdersList).DataTextField("PONumber").DataValueField("PurchaseOrderID").OptionLabel("Select")
#Html.ValidationMessageFor(model => model.PurchaseOrdersList)
</div>
<div class="editor-label">
Invoice Ref.
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.InvoicNo, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.InvoicNo)
</div>
<br />
<div class="editor-label">
</div>
<div class="editor-field">
<input type="submit" value="Save" class="k-button" />
</div>
</div>
</fieldset>
}
ViewModel:
public class StockReceiptViewModel
{
public int StockReceiptID { get; set; }
[Required(ErrorMessage = "Required")]
public int SupplierID { get; set; }
[Required(ErrorMessage = "Required")]
public int MaterialID { get; set; }
[Required(ErrorMessage = "Required")]
public DateTime? ReceiptDate { get; set; }
[Required(ErrorMessage = "Required")]
public int Quantity { get; set; }
public int? QuantityReserved { get; set; }
[Required(ErrorMessage = "Required")]
public decimal? SlabWidth { get; set; }
[Required(ErrorMessage = "Required")]
public decimal? SlabHeight { get; set; }
[Required(ErrorMessage = "Required")]
public int SizeUnits { get; set; }
[Required(ErrorMessage = "Required")]
public StockUnitsEnum StockUnitsEnum
{
get {return (StockUnitsEnum)SizeUnits;}
set {SizeUnits = (int)value;}
}
[Required(ErrorMessage = "Required")]
public string BatchReference { get; set; }
[Required(ErrorMessage = "Required")]
[DataType(DataType.Currency)]
public decimal? UnitCost { get; set; }
[Required(ErrorMessage = "Required")]
public int? NumberOfUnits { get; set; }
[Required(ErrorMessage = "Required.")]
public int PurchaseOrderID { get; set; }
[Required(ErrorMessage = "Required")]
public string InvoicNo { get; set; }
[Required(ErrorMessage = "Required")]
public decimal SlabCost { get; set; }
public bool IncludeTransport { get; set; }
[Required(ErrorMessage = "Required.")]
public int LocationID { get; set; }
public int? EnteredBy { get; set; }
public DateTime OnSystemFrom { get; set; }
public string Notes { get; set; }
public List<SupplierViewModel> SuppliersList { get; set; }
public List<MaterialViewModel> MaterialsList { get; set; }
public List<LocationsViewModel> LocationsList { get; set; }
public List<PurchaseOrderViewModel> PurchaseOrdersList { get; set; }
public int LastModifiedBy { get; set; }
public DateTime LastModifiedDate { get; set; }
public int LiveQuantity { get; set; }
}
The Controller method has the ModelState.Isvalid check as well.
Please help if you can.
Many thanks.
You need to add jquery.unobtrusive and jquery.validate files to your views. Add this to your BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
And then render it on your _Layout View or in View you want validation:
#Scripts.Render("~/bundles/jqueryval")
If you are using default MVC template you should already have this bundle. Just make sure you have reference in your Views. You can check if your js files are loaded by using some web development tools like Firebug in Mozzila or press F12 in Chrome, and in NET tab you can see loaded scripts.
I have solved this problem by making sure that the method to where this form is submitting, is returning the viewmodel to the page (view) if ModelState.IsValid is false.
This is provided that the viewModel being returned is actually the same as the submitted one:
[HttpPost]
public ActionResult SaveSettings(StockReceiptViewModel stockReceiptVm)
{
try
{
if (ModelState.IsValid)
{
var stockReceipt = new StockReceipt();
if (stockReceiptVm.StockReceiptID != 0)
{
MapViewModelToModel(stockReceiptVm, stockReceipt);
stockReceipt.LastModifiedBy = UserHelper.GetCurrentUserIDByEmail();
stockReceipt.LastModifiedDate = DateTime.Now;
//update
_stockReceiptRepository.UpdateStockReceipt(stockReceipt, stockReceiptVm.StockReceiptID);
}
else
{
MapViewModelToModel(stockReceiptVm, stockReceipt);
stockReceipt.EnteredBy = UserHelper.GetCurrentUserIDByEmail();
stockReceipt.OnSystemFrom = Utilities.RemoveTimeFromDate(DateTime.Now);
//save new
_stockReceiptRepository.InsertStockReceipt(stockReceipt);
}
return RedirectToAction("Index", "StockReceiptsGrid");
}
SetupViewDropdownLists(stockReceiptVm);
return View("Index", stockReceiptVm);
}
catch (Exception exc)
{
ErrorHelper.WriteToEventLog(exc);
return RedirectToAction("Index", "Error");
}
}

Resources