0

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>
user9448003
  • 87
  • 1
  • 10

2 Answers2

0

You can set the model type in view to:

@model IEnumerable<WebApplication2.Models.Strategy>

and on the view:

if(Model != null)
{
    foreach(var strategy in Model)
    {
        //strategy should give you all the details you need
    }
}
sorak
  • 2,607
  • 2
  • 16
  • 24
Fancy5g
  • 99
  • 4
  • Yes I know that is a possible solution but I would like to call the model in in the beginning of the view. Like in the DropdownlistFor. When I set the model to IEnumerable then it would not let me call the model(m=>m.OSR) for the DropdownList. – user9448003 Mar 16 '18 at 19:24
0

Imagine you had a StategyViewModel. In the case where you have views that present more than a single type, you will find it easier to organize these types in a super type (the 'ViewModel' type).

Read about The MVVM Pattern

In this case, instead of...

Model:

public class Strategy
{
    public string name;

    // all your other properties...
}

View:

@model WebApplication2.Models.Strategy

    <!-- present some stuffs... -->

Controller:

public ActionResult Index()
{
    var strategy = new Strategy();  // a concrete model type/class

    // do some stuffs...

    // using ViewBag to pass a bag of stuffs...

    return View(strategy);
}

Change to this...

The ViewModel:

public class StrategyViewModel
{
    public Strategy strategy;
    public string someString;  // instead of ViewBag'ing everything?
}

View:

@model WebApplication2.ViewModels.StrategyViewModel

    <!-- present some stuffs... -->

Controller:

public ActionResult Index()
{
    var vm = new StrategyViewModel();

    // do some stuffs...

    return View(vm);
}
Adam Cox
  • 3,341
  • 1
  • 36
  • 46
  • I created a View Model that contains the model Strategies and the ienumerable...I'm still getting the error: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[WebApplication2.Models.Strategy]', but this dictionary requires a model item of type 'WebApplication2.Models.StrategyVM'. – user9448003 Mar 16 '18 at 20:32
  • Is your code in question current? If so, then change model in view to use the new viewmodel type `StrategyVM`, and be sure to do 2 things in your controller... 1) declare a new viewmodel type like `var vm = new StrategyVM` and 2) pass this type back to view like `return View(vm);` – Adam Cox Mar 16 '18 at 21:00