locked
The model item passed into the dictionary is of type A but this dictionary requires a model item of type B RRS feed

  • Question

  • User2057184790 posted

    I am a beginner ASP.net coder. I understand that the controller is calling a List and the Model is calling a generic model and that this can be easily fixed be setting the model in the view to @model IEnumerable<WebApplication2.Models.Strategy>

    But I want to be able to call the model in the view so I can call it in my view. Below I posted my code.

    Controller:

    public ActionResult Index(string group, string prin, string status, string osr, string groupnew, string stratvar, string fltstring, Strategy selg, FormCollection form)
            {
    
                if (Session["UserId"] != null)
                {
                    Strategy strat = new Strategy();
    
                    int id = Int32.Parse(Session["UserId"].ToString()); // Get the user id from the session
                    String em = db.UserAccounts.Find(id).Email.ToString(); // Use the id to get the associated email address
                    EmailList emailListItem = db.EmailLists.First(x => x.Email == em); // Use the email address to get the associated emaillist object which holds the group
    
                    string perm = emailListItem.Perm;
    
                    if (perm == null)
                    {
                        perm = "0";
                    }
                    ViewData["perm"] = perm;
    
                    // if external
                    if (!emailListItem.IntExt)
                    {
                        // Create a list to hold the Todos which we will end up showing
                        List<Strategy> list = new List<Strategy>();
    
                        // this is a foreach loop, it goes through all the Todos returned from db.Todoes.ToList()
                        foreach (Strategy s in db.Strategies.ToList())
                        {
                            // makes sure that the group of a todo isn't null (empty)
                            if (!String.IsNullOrEmpty(s.Group))
                            {
                                // checks if the group of the user is equal to the group of the post. if so it adds the todo to the list.
                                if (emailListItem.Group.Equals(s.Group))
                                {
                                    list.Add(s);
                                }
                            }
                        }
    
                        return View(list);
    
                    }
                    else
                    {
                        // This is the query building code. 
                        string p = emailListItem.Perm;
                        string gr = emailListItem.Group;
                        StringBuilder sb = new StringBuilder();
                        sb.Append("SELECT * FROM dbo.Strategy WHERE "); //change table name for whatever you need returned
                        foreach (char c in p.ToCharArray())
                        {
                            if (group == null)
                            {
                                sb.Append("Perm LIKE '%");
                                sb.Append(c);
                                sb.Append("%' OR ");
                            }
    
                        }
                        sb.Length = sb.Length - 4;
    
    
                        if (selg == null)
                        {
    
                            List<Strategy> list = db.Strategies.SqlQuery(sb.ToString()).ToList(); //change table name
                            return View(list);
                        }
    
                        else
                        {
    
                            var groups = from g in db.Strategies
                                         select g;
                            var prins = from pr in db.Strategies
                                        select pr;
                            var osrs = from o in db.Strategies
                                       select o;
                            var statuss = from s in db.Strategies
                                          select s;
    
    
                            ViewBag.Groupcmb = (from g in db.Strategies.Include(p) where g.Group != null
                                             select g.Group).Distinct();
    
                            ViewBag.Principalcmb = (from pr in db.Strategies.Include(p) where pr.Principal != null
                                                 select pr.Principal).Distinct();
    
                            ViewBag.OSRcmb = (from o in db.Strategies.Include(p) where o.OSR != null
                                              select o.OSR).Distinct();
    
                            ViewBag.Statuscmb = (from s in db.Strategies.Include(p) where s.Status != null
                                              select s.Status).Distinct();
    
    
                            //ViewData["OSR"] = new SelectList(ViewBag.OSRcmb);
                            ViewBag.osrsel = osr;
    
                            //if all filters are null
                            if (group == null && stratvar == null && prin == null && osr == null && status == null)
                            {
                                return View(db.Strategies.ToList());
                            }
    
                            //returns same search filter for group if edit 
                            if (stratvar != null && group == null)
                            {
    
                                group = stratvar;
                                groups = groups.Where(g => g.Group.Contains(group));
                                //  return View(group.ToList());
                            };
    
    
    
                            if (prin != null && group != null && osr != null && status != null)
                           {
                                ViewBag.osrsel = osr;
                                prins = prins.Where(gpr => gpr.Principal.Contains(prin) && gpr.Group.Contains(group) && gpr.OSR.Contains(osr) && gpr.Status.Contains(status));
                                stratvar = null;
                                return View(prins.ToList());
                            }
    
    
                            return View(strat);
                        }
    
                    }
    
                }
                else
                {
                    return RedirectToAction("Login", "Account");
                }
    
            }

    View:

     @model WebApplication2.Models.Strategy
    
    <h2>Index</h2>
    
    <div class="col-md-6">
        @Html.ActionLink("Create New", "Create")
    </div>
    <div class="col-md-6">
        @if ((ViewData["perm"]).ToString() != "0")
        {
    
    
    
            using (Html.BeginForm())
            {
    
                <table>
                    <tr>
                        <td>Group</td>
                        <td>@Html.DropDownList("group", new SelectList(ViewBag.Groupcmb), "--Select--")</td>
                        <td>Status</td>
                        <td>@Html.DropDownList("status", new SelectList(ViewBag.Statuscmb), "--Select--")</td>
                        <td>Principal</td>
                        <td>@Html.DropDownList("prin", new SelectList(ViewBag.Principalcmb), "--Select--")</td>
                        <td>OSR</td>
                        <td>@Html.DropDownListFor(m => m.OSR, new SelectList(ViewBag.OSRcmb), "--Select--")</td>
                        <td>
                            <input type="submit" value="Search" onclick="location.href='@Url.Action("Index", "Strategy")'" />
                        </td>
                    </tr>
                </table>
    
    
            }
    
        }
        else if ((ViewData["perm"]).ToString() == "0")
        {
            <div class="col-md-6 hide">
    
                @using (Html.BeginForm())
                {
    
                }
            </div>
        }
    
    </div>
    <div class="col-md-12"></div>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Customer)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Product)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Status)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NextAction)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Updated)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FollowUpDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.OSR)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Principal)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Value)
            </th>
            <th></th>
        </tr>
    
        @*@foreach (var item in Model)
            {*@
        <tr>
            <td>
                @Html.DisplayFor(model => model.Customer)
            </td>
            <td>
                @Html.DisplayFor(model => model.Product)
            </td>
            <td>
                @Html.DisplayFor(model => model.Status)
            </td>
            <td>
                @Html.DisplayFor(model => model.NextAction)
            </td>
            <td>
                @Html.DisplayFor(model => model.Updated)
            </td>
            <td>
                @Html.DisplayFor(model => model.FollowUpDate)
            </td>
            <td>
                @Html.DisplayFor(model => model.OSR)
            </td>
            <td>
                @Html.DisplayFor(model => model.Principal)
            </td>
            <td>
                @Html.DisplayFor(model => model.Value)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = Model.StrategyId, group = Model.Group }) |
                @Html.ActionLink("Details", "Details", new { id = Model.StrategyId })
                @*|*@
             </td>
        </tr>
    </table>

    Friday, March 16, 2018 6:58 PM

All replies

  • User475983607 posted

    The problem is straightforward.  If the View's model is declared as @model WebApplication2.Models.Strategy, then the action must pass a WebApplication2.Models.Strategy type.  Currently the code is passing a List<WebApplication2.Models.Strategy> and depending on conditions a single WebApplication2.Models.Strategy.  

    The hard part is we can't make a recommendation because it is not clear if the problem is the View or the Controller.

    Other than that the code has other issues.  You should never do this...

     if (Session["UserId"] != null)

    ASP comes with Identity services and you should use the built in Identity system.

    The controller logic has a lot of, what looks like, business logic.  This code logic should be moved to a business layer; another class. 

    Friday, March 16, 2018 7:23 PM
  • User1120430333 posted

    I am a beginner ASP.net coder. I understand that the controller is calling a List and the Model is calling a generic model and that this can be easily fixed be setting the model in the view to
    @model IEnumerable<WebApplication2.Models.Strategy>
    But I want to be able to call the model in the view so I can call it in my view. Below I posted my code.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.+

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

    <end>

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    Saturday, March 17, 2018 7:36 AM
  • User-707554951 posted

    Hi jamiie

    From the title and content in this thread, it is hard for us to find what is your problem,

    So, would you please provide detailed description on the following description.

    But I want to be able to call the model in the view so I can call it in my view.

    Best regards

    Cathy

    Wednesday, March 21, 2018 8:01 AM