Link to home
Start Free TrialLog in
Avatar of Intelli-Seeker
Intelli-SeekerFlag for United States of America

asked on

MVC 5 error saving to database - Get method uses one model and post uses a different model

I am trying to get data from one model and post to another. I am getting an error:

"The model item passed into the dictionary is of type 'CRM.Models.Meeting', but this dictionary requires a model item of type 'CRM.Models.MeetingModel'."


I am certain that it is a simple syntax error. I just don't know what I am missing. If needed, I can provide the syntax of the models also. I have a model called MeetingModel and a model that was derived from Entity Framework that is named Meeting.

Meetings Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CRM.Models;
using PagedList;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace CRM.Controllers
{
    public class MeetingsController : Controller
    {
        private CRMEntities db = new CRMEntities();

// GET: Meetings/Create
public ActionResult Create(int customerId)

        {
            var snapshots = db.Accounts.Where(x => x.Customer == customerId)
                .Select(x => new SnapshotModel
                {
                    AccountNumber = x.AccountNumber,
                    System = x.System,
                    Category = x.Category,
                    Balance = x.Balance,
                }).ToList();
            var model = new MeetingModel
            {
                Customer = customerId,
                Snapshots = snapshots,
            };
            if (model.ConfidenceRating==null)
            {
                model.ConfidenceRating = new SelectList(new List<SelectListItem>(){

                    new SelectListItem(){Text="Undefined", Value="0"},
                    new SelectListItem(){Text="Very Stable", Value="1"},
                    new SelectListItem(){Text="Stable", Value="2"},
                    new SelectListItem(){Text="At Risk", Value="3"},
                }, "Value", "Text");
            }

            //Add upload capability to Create Meeting view
            foreach (string upload in Request.Files)
            {
                if (Request.Files[upload].FileName != "")
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + "~/uploads/";
                    string filename = Path.GetFileName(Request.Files[upload].FileName);
                    Request.Files[upload].SaveAs(Path.Combine(path, filename));
                }
            }

            ViewBag.Customer = new SelectList(db.Meetings, "Id", "Customer1.Name");
            ViewBag.Employee = new SelectList(db.Employees.OrderBy(e => e.FullName), "FullName", "FullName");
            return View(model);
        }

// POST: Meetings/Create
[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,InteractionDate,Notes,approval_status_id,CustomerCallDecisionedBy,CustomerCallDecisionDate,BankOfficer,TrustOfficer,Customer,Employee,IsDeleted,/*ConfidenceRating,*/IsReview,Purpose,FollowUpItems")] Meeting meeting, HttpPostedFileBase upload)

        {
            if (ModelState.IsValid)
            //Add upload capability to the create meeting view
            {
                List<Attachment> attachments = new List<Attachment>();
                for (int i = 0; i <Request.Files.Count; i++)
                {
                    var file = Request.Files[i];
                    if(file != null && file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var id = Guid.NewGuid().ToString();
                        Attachment attachment = new Attachment()
                        {
                            Name = fileName,
                            Path = id + Path.GetExtension(upload.FileName),
                        };
                        attachments.Add(attachment);
                        var path = Path.Combine(Server.MapPath("~/uploads"), attachment.Path);
                        file.SaveAs(path);
                    }
                }
            //Add Account List to create view
                foreach (var account in db.Accounts.Where(x => x.Customer == meeting.Customer))
                {
                    var snapshot = new Snapshot
                    {
                        AccountNumber = account.AccountNumber,
                        System = account.System,
                        Category = account.Category,
                        Balance = account.Balance,
                    };

                    meeting.Snapshots.Add(snapshot);
                }
                meeting.Attachments = attachments;
                db.Meetings.Add(meeting);
                db.SaveChanges();
                return RedirectToAction("Details", new { Id = meeting.Id });
            }
                return View(meeting);
        }

Open in new window

Create view:

@model CRM.Models.MeetingModel

@{
    ViewBag.Title = "Create Meeting";
}

<h2>Create Meeting</h2>
@using (Html.BeginForm("Create", "Meetings", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(x => x.Customer)
<div class="form-horizontal">
 @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.InteractionDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-6">
            @Html.EditorFor(model => model.InteractionDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.InteractionDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Purpose, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Purpose, 5, 145, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Purpose, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Notes, 5, 145, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.FollowUpItems, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.FollowUpItems, 5, 145, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FollowUpItems, "", new { @class = "text-danger" })
        </div>
    </div>
<div class="form-group">
        @Html.LabelFor(model => model.Customer1.BankOfficer, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-6">
            @Html.EditorFor(model => model.Customer1.BankOfficer, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Customer1.BankOfficer, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.TrustOfficer, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-6">
            @Html.EditorFor(model => model.TrustOfficer, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.TrustOfficer, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee, "Employee", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-6">
            @Html.DropDownList("Employee", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee, "", new { @class = "text-danger" })
        </div>
    </div>
 <div class="form-group">
        @Html.LabelFor(model => model.ConfidenceRating, "Confidence Rating", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(c => c.ConfidenceRating, Model.ConfidenceRating, "Please Select Confidence Rating")
            @Html.ValidationMessage("Confidence Rating is required.")
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.IsReview, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.IsReview)
                @Html.ValidationMessageFor(model => model.IsReview, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
<div class="form-group">
        @Html.Label("Attachment", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" multiple="multiple" id="Attachment" name="upload">
        </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>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Open in new window


Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

You cannot use your Meeting model view. You shall map to a DB entity. For example you can change your controller as follows: (replace lines 92 to 108)
   //Add Account List to create view
   var dbMeeting = new CRM.Models.Meeting();
   //map from MVC model to DB model, for example:
   dbMeeting.Id = meeting.Id;
   dbMeeting.Customer = meeting.Customer;
   foreach (var account in db.Accounts.Where(x => x.Customer == meeting.Customer))
   {
      var snapshot = new Snapshot
      {
         AccountNumber = account.AccountNumber,
         System = account.System,
         Category = account.Category,
         Balance = account.Balance,
      };


      dbMeeting.Snapshots.Add(snapshot);
   }
   dbMeeting.Attachments = attachments;
   db.Meetings.Add(dbMeeting);
   db.SaveChanges();

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.