1

I am working on a basic CRUD .net MVC application, with a requirement to validate the same data differently depending on if it is being created or edited.

As per the answer to the following question, it seems a different model for create and edit is required.

I have tried adding a class to the current model, with the following error:

"Multiple object sets per type are not supported. The object sets
'ReportDetails' and 'ReportDetailsEdit' can both contain instances 
of type 'Test.Models.ReportDetails'."

I have also tried creating a new model, with the following error:

 The namespace 'Test.Models' already contains a definition for 'TestDBContext'

What is the correct way to achieve this?

Here is a current basic outline of the model and controller:

Model:

public class ReportDetails {
    [Key]
    public int ReportID { get; set; }

    [Required]
    public string Email { get; set; }

    [NotMapped]
    [Compare("Email", ErrorMessage = "Confirmation field must match")]
    public string ConfirmEmail { get; set; }

    //Further fields here
}

Controller:

[HttpPost]
    public ActionResult Edit(ReportDetails reportdetails) {
        if (ModelState.IsValid) {
            db.Entry(reportdetails).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(reportdetails);
    }

The model is currently used for both create and edit, although I do not want the confirm email field included in addition to different validation rules for further fields.

Community
  • 1
  • 1
BroxSB
  • 11
  • 2
  • Show some code so we can understand what your trying to do (you should have one data model but 2 different view models is you need different validation) –  Oct 26 '15 at 10:37
  • Thanks, I have updated with code samples of my model and controller – BroxSB Oct 26 '15 at 10:49
  • Your data model should contain only 2 properties - `ReportID` and `Email`. Then you have view models containing the properties you need in each view with the appropriate validation attributes (and map from the data model to the view model in the GET and vice versa in the POST methods. - refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Oct 26 '15 at 10:52

0 Answers0