Note that there are some explanatory texts on larger screens.

plurals
  1. POValidationResult and ViewModels
    text
    copied!<p>I have recently created a new application that is using MVC4 and EF5. The tables already existed, so we are using Database first. This is all new to me, it is my first time in MVC or EF.</p> <p>I have some models in my EMDX file, and in one of them I inherited IValidatableObject and put some code in the Validate function. This was working fine, then I changed my view to use a ViewModel, now I get an error from validate, and I am stumped. It is still calling my validate function, but no longer posting it back to the screen, i just get a yellow screen.</p> <p>Error:</p> <pre><code>Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. </code></pre> <p>Model:</p> <pre><code>public partial class Names : IValidatableObject { public int Id { get; set; } public string Name { get; set; } public bool Active { get; set; } public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext) { // some logic, this works } } </code></pre> <p>ViewModel:</p> <pre><code>public class NamesVM { public Names Name { get; set; } // some other stuff in this model, but not part of this problem } </code></pre> <p>Controller: Edit Function:</p> <pre><code>[HttpPost] public ActionResult Edit(NamesVM nvm) { if (ModelState.IsValid) { dbCommon.Entry(nvm.Name).State = EntityState.Modified; dbCommon.SaveChanges(); return RedirectToAction("Index"); } return View(nvm); } </code></pre> <p>View:</p> <pre><code>@model NamesVM &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Name.Id) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Name.Id) @Html.ValidationMessageFor(model =&gt; model.Name.Id) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Name.Name) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Name.Name) @Html.ValidationMessageFor(model =&gt; model.Name.Name) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Name.Active) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Name.Active) @Html.ValidationMessageFor(model =&gt; model.Name.Active) &lt;/div&gt; &lt;input type="submit" value="Save" /&gt; </code></pre> <p>The codes works fine if everything is correct on the screen, but when validation fails, i don't get a nice error, I get a yellow screen. I am sure I am missing something, I just don't know what.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload