Why my DateTime ModelState is invalid? - asp.net-mvc

I have a model like this. Basically I have a field for a class name and two fields for start and end date in format of MM/dd/yyyy
namespace WebApplication3.Models
{
public class DateTimeViewModel
{
public DateTimeViewModel()
{
StartDate = new DateTime(DateTime.Today.Year, 1, 1);
EndDate = new DateTime(StartDate.Year, 12, 31);
}
public int Id { get; set; }
public string ClassName { get; set; }
[Display(Name = "Start Date")]
[Required(ErrorMessage = "{0} is required")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[Required(ErrorMessage = "{0} is required")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
}
}
This is my View
#model WebApplication3.Models.DateTimeViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DateTimeViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ClassName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClassName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClassName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndDate, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
This is my HttpPost controller
[HttpPost]
public ActionResult Create(WebApplication3.Models.DateTimeViewModel model)
{
if(ModelState.IsValid)
{
/// do something
}
return View();
}
The problem I am having now is that my ModelState.IsValid is returning FALSE when I enter a day like as in picture below:
It looks like every time I am entering a Day that is bigger than 12 then I'll get the validation error.
Do you know why or what I am doing wrong here?
Thank you so much.

Add the culture in your web config file:
<system.web>
<globalization uiCulture="en" culture="en-GB"/>
And add in your global asax this:
protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo culture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
Hope this help.

Add [DataType(DataType.Date)] to your annotations.

Related

Display name of Identity User who created and last updated record when ID is saved

I must not be searching with the correct phrases. This is a simple concept and I’ve done it in other languages and frameworks with ease.
I’m saving the UserID for the person who created the record and the UserID who last updated the record. Instead of displaying the UserID, I want to display the User.FirstName + ‘ ‘ + User.LastName.
The way I have it currently the LastEditBy and CreateBy is displayed on the page as blank.
Controller: I get the customer model and manually map the model to the customerViewModel then pass it to my partial view.
public ActionResult Edit(int customerId)
{
Customer customer = DbContext.Customers.FirstOrDefault(x => x.CustomerId == customerId);
CustomerViewModel customerViewModel = MapToViewModel(customer);
customerViewModel.UserSelectList = GetUserGroupList();
UserManager<ApplicationUser> _userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>();
var CreateByUser = _userManager.FindById(customerViewModel.CreateById);
var EditByUser = _userManager.FindById(customerViewModel.LastEditById);
customerViewModel.CreateBy = CreateByUser.FirstName + " " + CreateByUser.LastName;
customerViewModel.LastEditBy = EditByUser.FirstName + " " + EditByUser.LastName;
if (Request.IsAjaxRequest()) {
return PartialView("_CustomerEditPartial", customerViewModel);
}
return View("_CustomerEditPartial", customerViewModel);
}
The CustomerViewModel:
public class CustomerViewModel : DbContext{
public CustomerViewModel(): base("name=CustomerViewModel")
{
}
[Key]
public int CustomerId { get; set; }
[MaxLength(128), ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public SelectList UserSelectList { get; set; }
#region additional Fields
// This overrides default conventions or data annotations
[Required(ErrorMessage = "Please enter your first name.")]
[StringLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your last name.")]
[StringLength(100)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreateDate { get; set; } = DateTime.Now;
public string CreateById { get; set; }
[NotMapped]
public string CreateBy { get; set; }
public string LastEditById { get; set; }
[NotMapped]
public string LastEditBy { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LastEditDate { get; set; } = DateTime.Now;
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class UserGroupList
{
public string Value { get; set; }
public string Text { get; set; }
}
My partial view page: _CustomerEditPartial.cshtml
#model WOA.ViewModels.CustomerViewModel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" daa-dismiss="modal" aria-hidden="True">x</button>
<h4 class="modal-title">Edit Customer</h4>
</div>
#using (Ajax.BeginForm("Edit", "Customers", null, new AjaxOptions { HttpMethod = "Post", OnFailure = "OnFail" }, new { #class = "form-horizontal", role = "form" })) {
<div class="modal-body">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.CustomerId)
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, ViewData.Model.UserSelectList, "Select One", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateDate, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditDate, new { #readonly = "readonly" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save changes" />
</div>
</div>
</div>
<script type="text/javascript">
function OnSuccess() {
alert("success");
}
function OnFail() {
alert("fail");
}
function OnComplete() {
alert("Complete");
}
</script>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I have updated my code, it is working now, however I do not believe it is the proper way to do this.
I believe I should be able to return the additional values I need via Linq on the initial call and not make two more trips to the database for the additional values.
I have not been able to figure out a way to make this work with Linq.
Thank you in advance for your time and effort.

ASP.NET MVC Route Parameter replacing Model Field

I am testing an ASP.NET MVC 5 application with Visual Studio 2017 Community edition.
I am trying to save Assort model to database with following code.
I am navigating to Assort Create page with URL /Assort/Create/1A.
The parameter 1A is needed on create page of Assort as I need to display some additional information from that parameter on create page itself.
But when I submit the data, 1A parameter value is being inserted as ID value of Assort model, and thus my ModelState is invalid and I am unable to save data.
Can anyone help me?
MODEL
public class Assort
{
[Key]
public int ID { get; set; }
[Display(Name = "Assort No")]
[Required(ErrorMessage = "Assort No can not be empty.")]
public int ASSORTNO { get; set; }
[Display(Name = "Date")]
[Required(ErrorMessage = "Date can not be empty.")]
public DateTime DATE { get; set; }
[Display(Name = "RFNO")]
[Required(ErrorMessage = "RFNO can not be empty.")]
[StringLength(50)]
public string RFNO { get; set; }
[Display(Name = "Manager")]
[Required(ErrorMessage = "Manager can not be empty.")]
public int MANAGER { get; set; }
[Display(Name = "Caret")]
[Required(ErrorMessage = "Caret can not be empty.")]
public decimal CARET { get; set; }
[Display(Name = "MFG Size")]
[Required(ErrorMessage = "MFG Size can not be empty.")]
public decimal MFGSIZE { get; set; }
[Display(Name = "Total PCS")]
[Required(ErrorMessage = "Total PCS can not be empty.")]
public decimal TOTALPCS { get; set; }
[StringLength(50)]
public string APPROVALSTATUS { 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; }
[UIHint("AssortReturn")]
public virtual List<AssortReturn> AssortReturn { get; set; }
public Assort()
{
AssortReturn = new List<AssortReturnModel.AssortReturn>();
}
[ForeignKey("RFNO")]
public virtual Rough rough { get; set; }
}
ACTION
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Assort assort)
{
if (ModelState.IsValid)
{
assort.APPROVALSTATUS = "NOT APPROVED";
assort.CREATE_TIMESTAMP = DateTime.Now;
assort.LAST_EDIT_TIMESTAMP = DateTime.Now;
db.Assorts.Add(assort);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize(assort.RFNO,"CREATE");
return View(assort);
}
VIEW
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ASSORTNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ASSORTNO, new { htmlAttributes = new {#readonly="readonly",#Value=ViewBag.ASSORTNO, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ASSORTNO, "", 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.EditorFor(model => model.DATE, new { htmlAttributes = new {#autofocus="autofocus",#Value=ViewBag.CURRENTDATE, #class = "form-control date" } })
#Html.ValidationMessageFor(model => model.DATE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RFNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RFNO, new { htmlAttributes = new { #readonly = "readonly", #Value = ViewBag.RFNO, #class = "form-control" } })
#Html.TextBox("AVAILABLECARET",(decimal)ViewBag.AVAILABLECARET,new {#class="form-control txtAvailablecaret",#readonly="readonly" })
#Html.ValidationMessageFor(model => model.RFNO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MANAGER, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.MANAGER, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DropDownListFor(model => model.MANAGER, new SelectList(ViewBag.MANAGERLIST, "ID", "USERNAME"), "Select Manager", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MANAGER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CARET, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CARET, new { htmlAttributes = new { #class = "form-control txtCaret" } })
#Html.ValidationMessageFor(model => model.CARET, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MFGSIZE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MFGSIZE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MFGSIZE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TOTALPCS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TOTALPCS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TOTALPCS, "", 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 class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default btnCreate" />
</div>
</div>
</div>
}
This is because of the default route, which is handling your request. It looks like:
{controller}/{action}/{id}
And so A1 gets bound to ID. If you want a different behavior, say A1 is still a part of the URL, but binds to a different param, say "name", you need a new route for that:
routes.MapRoute(
name: "CreateAssort",
url: "Assort/Create/{name}",
defaults: new { controller = "Assort", action = "Create"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now "name" will hold A1 and not ID. Notice how your custom route comes before the default one. This is important - routing picks the first route that matches the request.
What you can do is add a hidden input field named ID to your view.
When the form will be submitted, the value from this field will take precedence over the one from your route i.e. '1A' and the model would have ID as 0 if you don't set the hidden input's value.
I had same issue. But problem is when you creating an model.
You need to have two methods.
[HttpGet] // http://localhost/Assort/Create/1
public ActionResult Create(int Id)
{
ModelState.Remove(nameof(Id)); // this will remove binding
var assort = new Assort()
{
Id = 'whatever',
....
};
return View(assort);
}
[HttpPost] // http://localhost/Assort/Create/
public ActionResult Create(Models.Assort assort)
{
if (ModelState.IsValid)
{
assort.APPROVALSTATUS = "NOT APPROVED";
assort.CREATE_TIMESTAMP = DateTime.Now;
assort.LAST_EDIT_TIMESTAMP = DateTime.Now;
db.Assorts.Add(assort);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize(assort.RFNO,"CREATE");
return View(assort);
}
C# ASP MVC Route Model ID bug

Getting vailidation anomalies in MVC

I'm following this (https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part7), but I am seeing some strange things I when I view the webpage.
1) The ReleaseDate says its a required filed (even though its not marked as such in the code) , and I cannot see why its doing this.
and
2) the Price "works" if the values is 100.50, or less . if its 100.51 or higher, then the message kicks in. My understanding is that the message should kick in # 100.01... or am I wrong ?
namespace Movies.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Movie
{
public int Id { get; set; }
[Required(ErrorMessage = "Titles are required")]
public string Title { get; set; }
public System.DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Required(ErrorMessage = "The Price is required.")]
[Range(5, 100, ErrorMessage = "Movies cost between £5 and £100.")]
public decimal Price { get; set; }
}
}
Could someone point out what I'm doing wrong ?
thanks
view code is
#model Movies.Models.Movie
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReleaseDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReleaseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Genre, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Genre, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Genre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
First question.
Make your DateTime nullable like this:
public System.DateTime? ReleaseDate { get; set; }
Second question:
Specify Range number type to double with literal d like this:
[Range(5d, 100d, ErrorMessage = "Movies cost between £5 and £100.")]
public decimal Price { get; set; }

ViewModel update failed with error

I am having following ViewModel, and corresponding two models.
I am displaying data from this ViewModel on a view, but when I post data to update, following error occurs
The model item passed into the dictionary is of type 'WebMSM.Models.ComplainDetailsVm', but this dictionary requires a model item of type 'WebMSM.Models.REPAIRING'.
public partial class ComplainDetailsVm
{
public virtual REPAIRING REPAIRINGs { get; set; }
public virtual COMPLAIN COMPLAINs { get; set; }
}
REPAIRING.cs
public partial class REPAIRING
{
[Key]
[DisplayName("JOBSHEET NO")]
public int JOBSHEET_NO { get; set; }
[DisplayName("IN TIME")]
public Nullable<System.DateTime> IN_TIMESTAMP { get; set; }
[DisplayName("CREATE TIME")]
public Nullable<System.DateTime> CREATE_TIMESTAMP { get; set; }
[DisplayName("LAST EDIT TIME")]
public Nullable<System.DateTime> LAST_EDIT_TIMESTAMP { get; set; }
}
COMPLAIN.cs
public partial class COMPLAIN
{
[Key]
[DisplayName("JOBSHEET NO")]
public int JOBSHEET_NO { get; set; }
[Required]
[DisplayName("COMPANY NAME")]
public string COMPANY_NAME { get; set; }
[Required]
[DisplayName("MODEL NAME")]
public string MODEL_NAME { get; set; }
}
CONTROLLER ACTION
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id,ComplainDetailsVm model)
{
if (ModelState.IsValid)
{
var r = model.REPAIRINGs;
var c = model.COMPLAINs;
db.Entry(r).State = EntityState.Modified;
db.SaveChanges();
}
return View(model);
}
UPDATE
VIEW
#model WebMSM.Models.ComplainDetailsVm
#{
ViewBag.Title = "EditRepairingComplain";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.REPAIRINGs.JOBSHEET_NO)
#Html.HiddenFor(model => model.COMPLAINs.JOBSHEET_NO)
<div class="form-group">
#Html.LabelFor(model => model.COMPLAINs.COMPANY_NAME,
htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.TextBoxFor(model => model.COMPLAINs.COMPANY_NAME, new { #class = "form-control", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.COMPLAINs.COMPANY_NAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.COMPLAINs.MODEL_NAME, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.TextBoxFor(model => model.COMPLAINs.MODEL_NAME, new { #class = "form-control", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.COMPLAINs.MODEL_NAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.REPAIRINGs.IN_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.REPAIRINGs.IN_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.REPAIRINGs.IN_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.REPAIRINGs.CREATE_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.REPAIRINGs.CREATE_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.REPAIRINGs.CREATE_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.REPAIRINGs.LAST_EDIT_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.REPAIRINGs.LAST_EDIT_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.REPAIRINGs.LAST_EDIT_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-6">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
UPDATE ADDED GET METHOD
// GET: Repairing/Edit/5
public ActionResult Edit(int? id)
{
var vm = new ComplainDetailsVm();
var r = db.REPAIRINGs.Find(id);
var c = db.COMPLAINs.Find(id);
if (r != null)
{
vm.REPAIRINGs = r;
vm.COMPLAINs = c;
}
//ViewData["LIST_ESTIMATE_AMOUNT_OK_FROM_CUSTOMER"] = lstOKNOTOK;
return View("EditRepairingComplain",vm);
}
Thanks.
You can have your Views recognize your ViewModel in two ways: you can have the MVC framework figure that out for you, or you can use strongly typed views
In your case, your view is strongly typed but refers to the wrong object class. This can happen if you copied your view from some other file. You should see the following line on your cshtml file:
#model WebMSM.Models.REPAIRING
replace this with:
#model WebMSM.Models.ComplainDetailsVm
and you should no longer get the error.
Edit:
worth to mention that these lines should be on top of the cshtml file returned by the action methods.

The current request for action ... on controller type ... is ambiguous between the following action methods

When I run the application on browser with ~/Person/New the result is
The current request for action 'New' on controller type 'PersonController' is ambiguous between the following action method System.Web.Mvc.ActionResult New() on type PersonMVC.Controllers.PersonController System.Web.Mvc.ActionResult New(PersonMVC.Models.Person) on type PersonMVC.Controllers.PersonController
Model
namespace PersonMVC.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
[Required]
[DisplayName("Social Sequrity Number")]
[MinLength(11, ErrorMessage ="Social Security Number Must be 11 digit.")]
[MaxLength(11, ErrorMessage ="")]
public string SocialSecurityNumber { get; set; }
[DisplayFormat(DataFormatString ="{0:dd.MM.yyyy}")]
public DateTime BirthDay { get; set; }
}
}
-View
#model PersonMVC.Models.Person
#{
ViewBag.Title = "New";
}
<h2>New</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SocialSecurityNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SocialSecurityNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SocialSecurityNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BirthDay, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BirthDay, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller
namespace PersonMVC.Controllers
{
public class PersonController : Controller
{
public ActionResult New()
{
return View();
}
[HttpPost]
public ActionResult New(Person newPerson)
{
bool isTrue = ModelState.IsValid;
return View();
}
}
}
you need to decorate the method with appropriate http verb. Otherwise it will be considered as HttpPost usually.
i think adding [HttpPost] to the controller method would solve the problem

Resources