I cannot work out why does the Id property of my model not get validated by the modelstate.
This happens in a Create action, where the Id doesn't get returned from the view to the model, as it is only about to be generated.
The bottom line is, naturally, a desirable outcome, as validating a missing Id would only cause problems, but I cannot find any instructions which would tell modelstate to skip this property and I'd be keen to understand it better for later reuse.
I will also add, that all the properties of this model are marked as required.
EDIT: The indicated duplicate, points to a different problem.
What I am tryign to point at here, is that the ID attribute, does not go through validation at all, and not the fact that it passes the validation. Please see the modelstate pop-up box in attached screenshot, the modelstate does not look at the Id property at all.
Here's how it looks like in debugging:
The screenshot controllers is this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,ClientName")] Project project)
{
if (ModelState.IsValid)
{
//db.Entry(project).State = EntityState.Modified;
db.MarkAsModified(project);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(project);
My model is this:
public class Project
{
[Required]
public int Id { get; set; }
[Required]
[Display(Name = "Project name")]
public string Name { get; set; }
[Required]
public string ClientName { get; set; }
}
And the view that returns the user input is this:
@model Freelancer_DeveloperChallenge.Models.Project
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Project</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.ClientName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ClientName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ClientName, "", 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")
}